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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值