Python语言学习:属性 property

python 里的属性操作 set/get/del
更新于: 2022-02-11 05:50:05

类返回一个属性设置器

类里面就只有几个属性的情况

class C:
    def __init__(self, in_x):
        self._x = in_x

    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('lalala')
print(c.x)		# lalala

利用 property 装饰器

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

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


p1 = Parrot()
print(p1.voltage) 			# 100000

对 set/get/del 的实现进行详细的定制

class C:
    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

参考