版權聲明:本文為博主原創文章,遵循 CC 4.0 by-sa 版權協議,轉載請附上原文出處鏈接和本聲明。
重看狗書,看到對User表定義的時候有下面兩行
@property def password(self): raise AttributeError('password is not a readable attribute') @password.setter def password(self, password): self.password_hash = generate_password_hash(password)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
遂重溫下這個property的使用
在我們定義數據庫字段類的時候,往往需要對其中的類屬性做一些限制,一般用get和set方法來寫,那在python中,我們該怎么做能夠少寫代碼,又能優雅的實現想要的限制,減少錯誤的發生呢,這時候就需要我們的@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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
我們調用的時候需要這么調用:
>>> s = Student()
>>> s.set_score(60) # ok! >>> s.get_score() 60 >>> s.set_score(9999) Traceback (most recent call last): ... ValueError: score must between 0 ~ 100!
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
但是為了方便,節省時間,我們不想寫s.set_score(9999)啊,直接寫s.score = 9999不是更快么,加了方法做限制不能讓調用的時候變麻煩啊,@property快來幫忙….
class Student(object): @property def score(self): return self._score @score.setter def score(self,value): if not isinstance(value, int): raise ValueError('分數必須是整數才行吶') if value < 0 or value > 100: raise ValueError('分數必須0-100之間') self._score = value
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
看上面代碼可知,把get方法變為屬性只需要加上@property裝飾器即可,此時@property本身又會創建另外一個裝飾器@score.setter,負責把set方法變成給屬性賦值,這么做完后,我們調用起來既可控又方便
>>> 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!