Python functional property is the property: property attributes series of internal logic calculation, the results will eventually return.
Using property modified instance method is called, it can be the same as the instance properties
property usage 1-- decorator way
Application @property decorator instance method on a class
class Test:
def __init__(self):
self.__num = 100
@property
def num(self):
print("--get--")
return self.__num
@num.setter
def num(self, num):
print("--set--")
self.__num = num
t = Test()
print(t.num)
t.num = 1
"""
--get--
100
--set--
"""
Define and call property the property should pay attention to the following points:
- Defining added @property decorator on the basis of the example of the method; and only a self parameter.
- When you call, you do not need parentheses.
- Classic properties in only one access method, which corresponds to the modified method @property.
- The new class attributes, there are three access methods, and are respectively corresponding to the three @ property, @ method name .setter, @ .deleter method for modifying the method name.
Classes in Python classic classes and new classes, new classes of property than the rich class classic attributes. (If the class following the object, then the class is a new class), python3 the classes are new classes.
property usage 2-- class attribute way
When you create a property attribute using the class attribute way, Classic and new classes without distinction
class Test:
def __init__(self):
self.__num = 100
def setNum(self, num):
print("--set--")
self.__num = num
def getNum(self):
print("--get--")
return self.__num
# 注意:要先写get方法,再写set方法
aa = property(getNum, setNum)
t = Test()
print(t.aa)
t.aa = 1