Tag: Property Python property () Python built-in function
The property can access a Python-defined function as an attribute, 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:
Class cls (object): def __init__ (self): self.__x = none def getx (self) : return self.__x def setx (self, value): self.__x = value def delx ( Self): del self.__x x = property (getx, setx, delx, ' set x property ') if __name__ == ' __main__ ': c = cls () c.x = 100 y = c.x Print ("SET & GET&Nbsp;y: %d " % y) del c.x print ("del c.x & y: %d" % y)
Run Result: Set & get Y:100del c.x & Y:100 defines three functions in this class, respectively, as assignment, value, delete variable property function prototype as property (fget=none,fset=none,fdel= None,doc=none), the above example assigns a value according to its own definition of the corresponding function.
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
Class cls (object): def __init__ (self): self.__x = None @property def x (self): return self.__x @x.setter def X (Self, value): self.__x = value @x.deleter def x (self): del self.__x if __name__ == ' _ _main__ ': c = cls () c.x = 100 y = c.x print ("set & get y: %d" % y) &nbsP; del c.x print ("del c.x & y: %d " % y)
Run Result: Set & get Y:100del c.x & y:100 Description: The same property __x three function names.
This article is from the "Lu Yaliang" blog, make sure to keep this source http://luyaliang.blog.51cto.com/3448477/1767089
Python built-in function proprety ()