直接上代码:
1 #!/usr/bin/python 2 #encoding=utf-8 3 4 """ 5 @property 可以将python定义的函数“当做”属性访问,从而提供更加友好访问方式 6 """ 7 8 class Parrot: 9 #class Parrot(object): #报错,AttributeError: can't set attribute' 10 def __init__(self): 11 self._voltage = 10000 12 13 @property 14 def voltage(self): 15 return self._voltage 16 17 18 if __name__ == "__main__": 19 p = Parrot() 20 print p.voltage #就这样要调用函数,任性 21 p.voltage = 12 #给函数赋值,python中函数也是对象 22 print p.voltage
root@u163:~/cp/python# python property.py
10000
12