python中property的使用

记得在cocoa中也有property的概念,python中的property与cocoa里的property好像是差不多的。下面是它的两种用法。

用法一:

class test(object):
    def __init__(self):
        print "init is calling"
        self.a=100


    def getX(self):
        print "call getX"
        return self.a

    def setX(self,value):
        print "call setX"
        self.a=value

    x=property(getX,setX)


def main():
    a = test()
    print a.x  #100
    a.x=150
    print a.x  #150

if __name__ == '__main__':
    main()

getX和setX这两个函数名字可以随便取的。还有一个del方法,不太常用,所以这里就不写了

用法二:

class test(object):

    def __init__(self):
        print "init is calling"
        self.a=100

    @property
    def x(self):
        print "call getX"
        return self.a

    @x.setter
    def x(self,value):
        print "call setX"
        self.a=value



def main():
    t = test()
    print t.x  #100
    t.x=150
    print t.x  #150

if __name__ == '__main__':
    main()

注意到函数名都改成了x。

原文地址:https://www.cnblogs.com/streakingBird/p/4048636.html