Python學習(十三)--@property和property函數
阿新 • • 發佈:2018-07-08
span sin .com pre rac turn () 裝飾器 轉化
- @property
class Student(object): def get_score(self): return self._score def set_score(self, value): if not isinstance(value, int): raise然後通過@property裝飾器重新修改後:ValueError(‘score must be an integer!‘) if value < 0 or value > 100: raise ValueError(‘score must between 0 ~ 100!‘) self._score = value
class Student(object): @property def score(self): return self._score @score.setter把一個getter方法變成屬性,只需要加上@property。@property本身又創建了另外一個裝飾器@score.setter,把一個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 >>> s = Student() >>> s.score = 60 #OK,實際轉化為s.set_score(60) >>> s.score # OK,實際轉化為s.get_score() 60 >>> s.score = 9999 Traceback (most recent call last): ... ValueError: score must between 0 ~ 100!
- property函數
class Student(object): def get_score(self): return self._score 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 score = property(fget=get_score, fset=set_score) >>> s = Student() >>> s.score = 60 # OK,實際轉化為s.set_score(60) >>> s.score # OK,實際轉化為s.get_score() 60 >>> s.score = 9999 Traceback (most recent call last): ... ValueError: score must between 0 ~ 100!參考: https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386820062641f3bcc60a4b164f8d91df476445697b9e000
Python學習(十三)--@property和property函數