Python property() Function

Python 内置函数Python Built-in Functions


Description

property()The function is used to return attribute values in new-style classes.

Syntax

The following is the syntax of the property() method:

class property([fget[, fset[, fdel[, doc]]]])

Parameters

  • fget -- Function to get the attribute value
  • fset -- Function to set the attribute value
  • fdel -- Function to delete the attribute value
  • doc -- Attribute description information

Return Value

Returns new-style class attributes.

Examples

Define a controllable attribute 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.")

IfcYesCIf 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 will become the docstring of this attribute value; otherwise, the property function will copy the docstring of the fget function (if any).

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 getter, setter, and deleter methods of property 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 exactly the same as the first example, but note that the names of these additional functions are the same as those under property, such as x here.

Python 内置函数Python Built-in Functions

Other Extensions