呓语Beta 2.0 首页 镜头后 灶台前 捐赠者名单 有趣的小站

[python]类的property

文档信息

Property

使用方法

class WithoutProperty:
    def __init__(self):
        self._temperature = 20

class WithProperty:
    def __init__(self):
        self._temperature = 20

    @property
    def temperature(self):
        return self._temperature

class CompletedProperty:
    def __init__(self):
        self._temperature = 20

    @property
    def temperature(self):
        print('call temperature.getter')
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        print('call temperature.setter')
        self._temperature = value

    @temperature.deleter
    def temperature(self):
        print('call temperature.deleter')

if __name__ == '__main__':
    # 没有使用property
    without_property = WithoutProperty()
    print(without_property._temperature) # 输出默认值20
    without_property._temperature = 35 # 可以给成员变量赋值
    print(without_property._temperature) # 输出新值35

    # 使用Property
    with_property = WithProperty()
    print(with_property._temperature) # 仍然可以使用,但已经不作为接口
    print(with_property.temperature) # 输出默认值20,这里temperature是一个属性
    try:
        with_property.temperature = 35 # 无法赋值
    except:
        print('无法赋值')

    # 完整的Property
    completed_property = CompletedProperty()
    print(completed_property.temperature) # 调用getter
    completed_property.temperature = 35 # 调用setter 可以赋值
    print(completed_property.temperature) # 调用getter 查看新值
    del completed_property.temperature # 调用deleter

TIPS

参考文献

捐赠支持

可以使用支付宝转帐给richard.ma.19850509#gmail.com(请将#替换为@),谢谢!

Fork me on GitHub