YouTip LogoYouTip

Python Func Property

# Python2.x Python property() Function [![Image 3: Python Built-in Functions](#) Python Built-in Functions](#) * * * ## Description The **property()** function is used to return property values in new-style classes. ### Syntax Here is the syntax for the property() method: class property([fget[, fset[, fdel[, doc]]]]) ### Parameters * fget -- Function to get the property value * fset -- Function to set the property value * fdel -- Function to delete the property value * doc -- Property description information ### Return Value Returns a new-style class property. ### Example ## Define a controllable property value x class C(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, "I'm the 'x' property.") If _c_ is an instance of _C_, c.x will trigger the getter, c.x = value will trigger the setter, and del c.x will trigger the deleter. If the doc parameter is given, it becomes the docstring for this property; otherwise, the property function copies the docstring from the fget function (if it exists). Using the property function as a decorator makes it convenient to create read-only properties: class Parrot(object): def __init__ (self): self._voltage = 100000 @property def voltage(self): """Get the current voltage."""return self._voltage The code above converts the voltage() method into a getter method for a read-only property of the same name. The property's getter, setter, and deleter methods can also be used as decorators: class C(object): def __init__ (self): self._x = None @property def x(self): """I'm the 'x' property."""return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x This code is identical to the first example, but note that the names of these additional functions are the same as under property, for example, x here. [![Image 4: Python Built-in Functions](#) Python Built-in Functions](#)
← Python Func FilterPython Func File β†’