Python @property 属性

Python @property 修饰符

python的property()函数,是内置函数的一个函数, 会返回一个property的属性: 可以在以下网页查看它的描述:property

文档上面说property()作为一个修饰符, 这会创建一个只读的属性.

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

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

在这里面, @property修饰符会将voltage()方法转变为一个对于只读的属性"getter", 它还会将voltage的docstring设置为"Get the current voltage"

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

c = C()
c.X = 2
print(c.X)
print(c._x)
# 2
# 2

这个代码也能够使用非修饰符的方法来写, 请看下面

class C:
    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 = 2
print(c.X)
print(c._x)
# 2
# 2

这两段代码的意思, 就是通过property()设置了一个管理self._x的属性的函数, 以后管理_x, 都可以通过X这个property对象.

原文地址:https://www.cnblogs.com/hwy89289709/p/6697507.html