YouTip LogoYouTip

Python3 Func Property

Python property() Function /* Keep existing styles */

Python property() Function

The property() function is used to return the property attribute.

Grammar


property(fget=None, fset=None, fdel=None, doc=None)
        

Parameters

  • fget -- Get attribute function
  • fset -- Set attribute function
  • fdel -- Delete attribute function
  • doc -- Attribute description information

Return Value

Returns the property attribute.

Example

Using the property() function:


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.")

c = C()
c.x = 'XMAN'
print(c.x)
del c.x
        

Output:


XMAN
        

If the c.x is not defined, the following example shows how the property attribute works:


class Parrot:
    def __init__(self):
        self._voltage = 100000

    @property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage

    @voltage.setter
    def voltage(self, new_value):
        self._voltage = new_value

    @voltage.deleter
    def voltage(self):
        self._voltage = 0

p = Parrot()
print(p.voltage)
p.voltage = 220
print(p.voltage)
del p.voltage
        

Output:


100000
220
        
← Python3 Func VarsPython3 Func Iter β†’