在爲一個類實例綁定屬性時,若是咱們直接把屬性暴露出去,雖然寫起來很簡單,可是,沒辦法檢查參數,致使能夠把成績隨便改,甚至類型錯誤均可以。flask
class Student(object): def __init__(self, score): self.score = score if __name__ == '__main__': s = Student(100) print(s.score) s.score = 50 print(s.score) s.score = 'abc' print(s.score) ------------------------------ >>> 100 >>> 50 >>> abc
上述例子顯然不合邏輯,爲了限制score的範圍,能夠經過一個set_score()方法來設置成績,再經過一個get_score()方法來獲取成績,這樣,在set_score()方法裏就能夠檢查參數了。code
class Student(object): def set_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 def get_score(self): return self._score if __name__ == '__main__': s = Student() s.set_score(50) print(s.get_score()) s.set_score('abc') ------------------------------ >>> 50 >>> Traceback (most recent call last): File "/Users/luyuze/projects/myflask/App/test.py", line 18, in <module> s.set_score('abc') File "/Users/luyuze/projects/myflask/App/test.py", line 6, in set_score raise ValueError('score must be an integer !') ValueError: score must be an integer !
如今,對任意的Student實例進行操做,就不能爲所欲爲的設置score了。get
上面的調用方法雖然已經能夠實現相關功能,可是使用起來略顯複雜,設置和獲取屬性都須要經過調用方法來實現,沒有直接用屬性這麼簡潔明瞭。it
那麼,有沒有既能檢查參數,又能夠用相似屬性這樣簡單的方式來訪問類的變量呢?對於追求完美的python來講,這是必須作到的!ast
下面,咱們就使用python內置的裝飾器@property來實現。class
class Student(object): @property def score(self): return self._score @score.setter def 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 if __name__ == '__main__': s = Student() s.score = 50 # 實際轉化爲s.set_score() print(s.score) # 實際轉化爲s.get_score() s.score = 101 ------------------------------ >>> 50 >>> Traceback (most recent call last): File "/Users/luyuze/projects/myflask/App/test.py", line 21, in <module> s.score = 101 File "/Users/luyuze/projects/myflask/App/test.py", line 13, in score raise ValueError('score must between 0 - 100 !') ValueError: score must between 0 - 100 !
@property的實現比較複雜,咱們先考察如何使用,把一個getter方法變成屬性,只須要加上@property就能夠了,此時,@property自己又建立了另外一個裝飾器@score.setter,負責把一個setter方法變成屬性賦值,因而,咱們就擁有了如上例子中的屬性操做。test
注意到這個神奇的@property,咱們在對實例屬性操做的時候,就知道該屬性極可能不是直接暴露的,而是經過getter和setter方法來實現的。import
咱們還能夠定義只讀屬性,只定義getter方法,不定義setter方法就是一個只讀屬性。變量
import datetime class Student(object): @property def birth(self): return self._birth @birth.setter def birth(self, value): if not isinstance(value, int): raise ValueError('birth must be an integer !') self._birth = value @property def age(self): return datetime.datetime.now().year - self._birth if __name__ == '__main__': s = Student() s.birth = 1995 print(s.age) s.age = 25 ------------------------------ >>> 24 >>> Traceback (most recent call last): File "/Users/luyuze/projects/myflask/App/test.py", line 25, in <module> s.age = 25 AttributeError: can't set attribute
上面的birth是可讀寫屬性,而age就是一個只讀屬性,由於能夠根據birth和當前年份計算出來。
@property普遍應用在類的定義中,可讓調用者寫出簡短的代碼,同時保證對參數進行必要的檢查,這樣,程序運行時就減小了出錯的可能性。