標籤:python property 註解
裝飾器(decorator)可以給函數動態加上功能嗎?對於類的方法,裝飾器一樣起作用。Python內建
的 @property 裝飾器就是負責把一個方法變成屬性調用的:
class Student(object):@propertydef score(self):return self._score@score.setterdef score(self, value):if not isinstance(value, int):raise ValueError(‘score must be an integer!‘)if value < 0 or value > 100:raise ValueError(‘score must between 0 ~ 100!‘)self._score = value
@property 的實現比較複雜,我們先考察如何使用。把一個getter方法變成屬性,只需要加上 @property 就可以
了,此時, @property 本身又建立了另一個裝飾器 @score.setter ,負責把一個setter方法變成屬性賦值,於是,我
們就擁有一個可控的屬性操作:
>>> s = Student()>>> s.score = 60 # OK,實際轉化為s.set_score(60)>>> s.score # OK,實際轉化為s.get_score()60>>> s.score = 9999Traceback (most recent call last):...ValueError: score must between 0 ~ 100!
@property ,我們在對執行個體屬性操作的時候,就知道該屬性很可能不是直接暴露的,而是通過gett
er和setter方法來實現的。
還可以定義唯讀屬性,只定義getter方法,不定義setter方法就是一個唯讀屬性:
class Student(object): @property def birth(self): return self._birth @birth.setter #設定了set和get方法 def birth(self, value): self._birth = value @property #設定了get方法 def age(self): return 2014 - self._birthc=Student()c.birth=10;print c.age
D:\chinaUnicom\Chinese\python.exe D:/python/test1/test3.py2004Process finished with exit code 0
本文出自 “matengbing” 部落格,請務必保留此出處http://matengbing.blog.51cto.com/11395502/1905757
python中的property註解