Blame
|
1 | # Python Property |
||||||
| 2 | ||||||||
| 3 | ## Overview |
|||||||
| 4 | ```python |
|||||||
| 5 | class dog: |
|||||||
| 6 | def __init__(self): |
|||||||
| 7 | self._name = "Bello" |
|||||||
| 8 | ||||||||
| 9 | @property |
|||||||
| 10 | def name(self) -> str: |
|||||||
| 11 | print("Setter method called") |
|||||||
| 12 | return self._name |
|||||||
| 13 | ||||||||
| 14 | @name.setter |
|||||||
| 15 | def name(self, name): |
|||||||
| 16 | if isinstance(name, str): |
|||||||
| 17 | self._name = name |
|||||||
| 18 | print("Getter method called") |
|||||||
| 19 | else: |
|||||||
| 20 | return |
|||||||
| 21 | ``` |
|||||||
| 22 | ```python |
|||||||
| 23 | snowy = dog() |
|||||||
| 24 | snowy.name = "Snowy" |
|||||||
| 25 | snowy.name |
|||||||
| 26 | ``` |
|||||||
| 27 | ```python |
|||||||
| 28 | Setter method called |
|||||||
| 29 | Getter method called |
|||||||
| 30 | 'Snowy' |
|||||||
| 31 | ``` |
|||||||
| 32 | ||||||||
| 33 | ## Benefits |
|||||||
| 34 | - **@property**: for the caller name becomes an attribute (not a method any more) |
|||||||
| 35 | - no more use of parentheses when calling a getter: `a = snowy.name` instead of `a = snowy.name()` |
|||||||
| 36 | - the hidden getter still can return a deep copy or converted attribute (bytearray instead of byte, list instead of set, ...) |
|||||||
| 37 | - **@name.setter**: for the caller name can set by `=` |
|||||||
| 38 | - no more use of parentheses when calling a setter: `snowy.name = "Snowy"` instead of `snow.name("Snowy")` |
|||||||
| 39 | - the hidden setter still can use type checks or throw errors or do conversions |
|||||||
