Tweak documentation about _attr-style shorthand for properties (#999)

This commit is contained in:
Erik Montnemery 2021-07-08 11:21:43 +02:00 committed by GitHub
parent eee23aec0a
commit a4fd68603d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -89,7 +89,7 @@ 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
## Entity class or instance attributes
Writing property methods for each property is just a couple of lines of code,
for example
@ -105,8 +105,8 @@ class MySwitch(SwitchEntity):
...
```
Alternatively, a shorter form is to set Entity class attributes according to the
following pattern:
Alternatively, a shorter form is to set Entity class or instance attributes according to either of the
following patterns:
```python
class MySwitch(SwitchEntity):
@ -116,10 +116,23 @@ class MySwitch(SwitchEntity):
...
```
```python
class MySwitch(SwitchEntity):
def __init(self, icon: str) -> None:
_attr_icon = icon
...
```
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.
:::tip
If an integration needs to access its own properties it should access the property (`self.name`), not the class or instance attribute (`self._attr_name`).
:::
## Lifecycle hooks
Use these lifecycle hooks to execute code when certain events happen to the entity. All lifecycle hooks are async methods.