07.05 django rest framework
阿新 • • 發佈:2019-01-06
1.@property:Python內建的@property
裝飾器就是負責把一個方法變成屬性呼叫的
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
>>> 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!
class Student(object):
@property
def birth(self):
return self._birth
@birth.setter
def birth(self, value):
self._birth = value
@property
def age(self):
return 2014 - self._birth
上面的
birth
是可讀寫屬性,而
age
就是一個
只讀
屬性,因為
age
可以根據
birth
和當前時間計算出來。