Python property () function

property (): returns the new class attributes.

 

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

  • fget: get the property value
  • fset: set property values
  • fdel: Delete attribute values
  • doc: attribute description information

Example:

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 instantiation of C, cx will trigger getter, cx = value trigger setter, del cx trigger deleter.

Given doc parameter, this will be the docstring attribute value, or property function will copy docstring fget function (if any).

 

The property functions as a decorator can easily create a read-only attributes :

class Parrot(object):
    def __init__(self):
        self._voltage = 100000
 
    @property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage

Code Voltage () method of the getter converted to read-only property of the same name.

 

property of the getter, setter and deleter methods can also be used as decorator:

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 these additional function name and property, as for example where x.

 

Guess you like

Origin www.cnblogs.com/keye/p/10929224.html