From a4fd68603d681d0038d7ed74a0e2e5e0651c9b45 Mon Sep 17 00:00:00 2001 From: Erik Montnemery Date: Thu, 8 Jul 2021 11:21:43 +0200 Subject: [PATCH] Tweak documentation about _attr-style shorthand for properties (#999) --- docs/core/entity.md | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/docs/core/entity.md b/docs/core/entity.md index 051f5004..ce2815ab 100644 --- a/docs/core/entity.md +++ b/docs/core/entity.md @@ -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.