From 6a85f3685f0841d0f92199cdb35bbf0a8c918882 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Sat, 22 May 2021 18:19:19 +0200 Subject: [PATCH] Add information about using entity class attribute (#945) Co-authored-by: Teemu R. --- docs/core/entity.md | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/docs/core/entity.md b/docs/core/entity.md index 963f350b..051f5004 100644 --- a/docs/core/entity.md +++ b/docs/core/entity.md @@ -5,8 +5,6 @@ sidebar_label: Introduction For a generic introduction of entities, see [entities architecture](../architecture/devices-and-services.md). - - ## Basic implementation Below is an example switch entity that keeps track of their state in memory. @@ -91,6 +89,37 @@ The following properties are used and controlled by Home Assistant, and should n | ------- | ------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | enabled | boolean | `True` | Indicate if entity is enabled in the entity registry. It also returns `True` if the platform doesn't support the entity registry. Disabled entities will not be added to Home Assistant. | +## Entity class attributes + +Writing property methods for each property is just a couple of lines of code, +for example + +```python +class MySwitch(SwitchEntity): + + @property + def icon(self) -> str | None: + """Icon of the entity.""" + return "mdi:door" + + ... +``` + +Alternatively, a shorter form is to set Entity class attributes according to the +following pattern: + +```python +class MySwitch(SwitchEntity): + + _attr_icon = "mdi:door" + + ... +``` + +This does exactly the same as the first example. Properties that can be set +like this, start with `_attr_` followed by the property name. For example, +the `device_class` property, has the `_attr_device_class` class attribute. + ## Lifecycle hooks Use these lifecycle hooks to execute code when certain events happen to the entity. All lifecycle hooks are async methods.