Foreword
Today it is about @property decorator, which is a built-in decorative python, the main role is an attribute of a method of the class becomes class, and the definition of the properties and modify existing properties become easier
We can look at the source code examples and explanations given @property
1 Decorators make defining new properties or modifying existing ones easy: 2 3 4 class C(object): 5 @property 6 def x(self): 7 "I am the 'x' property." 8 return self._x 9 10 @x.setter 11 def x(self, value): 12 self._x = value 13 14 @x.deleter 15 def x(self): 16 del self._x
Yes, turtle t give explanation is that the decorator will define new properties and modify existing properties become more simple, less traditional approach is to do what and when binding properties access property?
Examples
. 1 "" " 2 ------------------------------------ . 3 @time: 2019/7/4 20:57 4 @Auth: Linux ultra 5 @file: python_property.py 6 @IDE: PyCharm 7 @Motto: Real Warriors, Dare to face at The Bleak warning, Dare to face at The Incisive error! 8 @ QQ: 28,174,043 @ QQ. COM . 9 @GROUP: 878.56576 million 10 ------------------------------------ . 11 "" " 12 is 13 is 14 class the UserInfo (Object): 15 16 DEF get_name (Self): . 17 "" " by the method of accessing the class in the class property " "" 18 return Self. __name__ . 19 20 is DEF set_name (Self, name): 21 is "" " Binding by an external parameter passing mode attribute " "" 22 is Self. __name__ = name 23 is 24 25 IF the __name__ == ' __main__ ' : 26 is User = UserInfo () 27 # bind name attribute 28 user.set_name ([ " super brother ", "linux super"] ) 29 Print ( "my name is : " , user.get_name ())
Results of the
My name is: [ 'ultra-brother', 'linux super']
Process Finished with Exit code 0
This way when binding properties, acquired properties was very cumbersome, and can not guarantee the accuracy of the data, from the results of view, the name should be a string of fishes, but the output is a list, which does not comply The actual rules
And there is no direct access to property, modify the properties so intuitive way
We make some changes to the code, and use the @property decorator to achieve
1 """ 2 ------------------------------------ 3 @Time : 2019/7/4 22:02 4 @Auth : linux超 5 @File : python_class.py 6 @IDE : PyCharm 7 @Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error! 8 @QQ : [email protected] 9 @GROUP: 878565760 10 ------------------------------------ 11 """ 12 13 14 class UserInfo(object): 15 @property 16 def name(self): 17 return self.__name 18 19 @name.setter 20 def name(self, name): 21 if isinstance(name, str): 22 self.__name = name 23 else: 24 raise TypeError("The name must be str") 25 26 27 if __name__ == '__main__': 28 user = UserInfo() 29 # 绑定属性 30 user.name = "linux超" 31 Print ( " My name is " , user.name) 32 user.name = [ " Linux super " , " super brother " ] 33 Print ( " My name is " , user.name)
Results of the
我的名字是 linux超 Traceback (most recent call last): File "D:/LingMengPython16/LingMengPython16/cnblogs/python_class.py", line 32, in <module> user.name = ["linux超", "超哥"] File "D:/LingMengPython16/LingMengPython16/cnblogs/python_class.py", line 24, in name raise TypeError("The name must be str") TypeError: The name must be str Process finished with exit code 1
After optimized code, we can see when the property is not binding when a string type, it will error, and we can directly attribute to bind a similar way to access the property, access to property, so the more intuitive
Here is a point to note, @ name.setter name in the name of his very being modified method name and @property modified method name must be consistent, otherwise it will error
@ Name.setter decoration which is due to the use @property decorator later created his own
In fact, I think @perproty decoration does not just only used to bind the property and access to property can also be used to access private member properties outside the class
First look at examples of external classes direct access to private members
1 """ 2 ------------------------------------ 3 @Time : 2019/7/4 20:57 4 @Auth : linux超 5 @File : python_property.py 6 @IDE : PyCharm 7 @Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error! 8 @QQ : [email protected] 9 @GROUP: 878565760 10 ------------------------------------ 11 """ 12 13 14 class UserInfo(object): 15 16 def __init__(self, name, age): 17 self.__name = name 18 self.__age = age 19 20 if __name__ == '__main__': 21 user = UserInfo('linux超', 18) 22 print(user.__name)
Results of the
Traceback (most recent call last): File "D:/LingMengPython16/LingMengPython16/cnblogs/python_property.py", line 22, in <module> print(user.__name) AttributeError: 'UserInfo' object has no attribute '__name' Process finished with exit code 1
Yes, the program is no way to run successfully, since python does not allow external access to the class you are in class private members, in fact, do so to protect the security of data
So this time we can use the property to access the class @property decorator
1 """ 2 ------------------------------------ 3 @Time : 2019/7/4 20:57 4 @Auth : linux超 5 @File : python_property.py 6 @IDE : PyCharm 7 @Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error! 8 @QQ : [email protected] 9 @GROUP: 878565760 10 ------------------------------------ 11 """ 12 13 14 class UserInfo(object): 15 16 def __init__(self, name): 17 self.__name= Name 18 is . 19 @Property 20 is DEF name (Self): 21 is "" " by the method of accessing a private class class attribute " "" 22 is return Self. __Name__ 23 is 24 IF the __name__ == ' __main__ ' : 25 User the UserInfo = ( ' Linux super ' ) 26 is Print ( " Get attribute name: " , the user.name)
Results of the
Gets the name attribute: linux super
Process finished with exit code 0
So you can access private members of the class of property
So in fact, I think, with respect to the binding properties is used more in this way, when you do not want to subclass inherits the parent class, subclass prevent modify the properties of the parent class, then you absolutely can use this method to avoid property is modified, and the outer sub-classes and also can access the private property
to sum up
@property decorator is mainly used as a method to change a property, and points to note
1. The method is decorated with the ornament does not pass any other parameters except the self
2. When both x and the need to ensure that the modified @ x.setter @property method name and method name modified to be consistent when using @property and @ x.setter