Python Property 属性

class Test(object): 
    def __init__(self):
        super(Test, self).__init__()

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

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

    num = property(getNum, setNum)


test = Test()
test.num = 20
print(test.num)

输出结果:

-set
-get
20

更加简介的方式如下:

class Test(object): 
    def __init__(self):
        super(Test, self).__init__()

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

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

test = Test()
test.num = 20 
print(test.num)

你可能感兴趣的:(Python Property 属性)