@property can access a python-defined function as a property, providing a more friendly way to access it, but sometimes setter/getter is Needed.
Suppose a class CLS is defined, which must inherit from the object class, with a private variable __x
1. The first method of using Attributes:
#!/usr/bin/env python#-*-coding:utf-8-*-#blog.ithomer.net classCls (object):def __init__(self): self.__x=NonedefGetx (self):returnSelf.__x defsetx (self, value): self.__x=valuedefDelx (self):delSelf.__xx= Property (getx, setx, delx,'set X property') if __name__=='__main__': C=Cls () c.x= 100y=c.xPrint("Set & get y:%d"%Y)delc.xPrint("del c.x & y:%d"% Y)
Operation Result:
Set & Get Y:100
Del c.x & y:100
Define three functions in the class, used as assignment, value, Delete variable
Property function prototype is property (fget=none,fset=none,fdel=none,doc=none), The above example according to their own definition of the corresponding function to assign a Value.
2. Second method (new in 2.6)
With method one, first define a class cls, which must inherit from the object class, with a private variable __x
?
classCls (object):def __init__(self): self.__x=None @propertydefx (self):returnSelf.__x@x.setterdefx (self, value): self.__x=value @x.deleterdefx (self):delSelf.__x if __name__=='__main__': C=Cls () c.x= 100y=c.xPrint("Set & get y:%d"%Y)delc.xPrint("del c.x & y:%d"% Y)
Operation Result:
Set & Get Y:100
Del c.x & y:100
Description: the three function names of the same property __x are the Same.
How to use Python accessor @property