property attribute
definition
A special keyword that can make an instance method be used like an instance attribute can correspond to a method. By using the property attribute, it can simplify the caller's process of obtaining data (make the code more concise).
The definition and call of property attributes should pay attention to the following points:
When calling, there is no need for parentheses, adding it is wrong; and there is only one self parameter
Two ways to implement property attributes
Decorator
The attributes in the new-style class have three access methods, and they correspond to three
- @property corresponding read
- @Method name.setter modification
- @Method name.deleter delete attribute
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
Class attribute
When using class attributes to create property attributes, the property() method has four parameters
- The first parameter is the method name, which automatically triggers the execution of the method when calling the object. property
- The second parameter is the name of the method, calling the object. The method is automatically triggered when the attribute = XXX
- The third parameter is the method name, which automatically triggers the execution of the method when calling the del object.
- The fourth parameter is a string, calling object.attribute.doc, this parameter is the description of the attribute
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
Use property instead of getter and setter methods
Use @property decorator to improve the get and set methods of private properties
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|