python中property属性的介绍及其应用

时间:2019-08-28 15:46:12   收藏:0   阅读:95

Python的property属性的功能是:property属性内部进行一系列的逻辑计算,最终将计算结果返回。
使用property修饰的实例方法被调用时,可以把它当做实例属性一样

property的用法1——装饰器方式

在类的实例方法上应用@property装饰器

class Test:
    def __init__(self):
        self.__num = 100

    @property
    def num(self):
        print("--get--")
        return self.__num

    @num.setter
    def num(self, num):
        print("--set--")
        self.__num = num

t = Test()
print(t.num)
t.num = 1
"""
--get--
100
--set--
"""

property属性的定义和调用要注意一下几点:

class Test:
    def __init__(self):
        self.__num = 100

    def setNum(self, num):
        print("--set--")
        self.__num = num

    def getNum(self):
        print("--get--")
        return self.__num

    # 注意:要先写get方法,再写set方法
    aa = property(getNum, setNum)


t = Test()
print(t.aa)
t.aa = 1

原文:https://www.cnblogs.com/lxy0/p/11424213.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!