python @propert裝飾器使用方法原理解析
這篇文章主要介紹了python @propert裝飾器使用方法原理解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
首先,@propert的作用是把類中的方法『變成』了屬性,方便通過實例訪問。propert可以有兩種用法:可以把一個方法變成只讀屬性;可以對一些屬性進行過濾。
想象這樣一個場景,在實例化一個類之后,需要對類的一個屬性進行賦值,這時候是沒有對屬性屬性被賦予的值進行判斷的,如果屬性被賦予了一個不合適的值,那么代碼在后面執(zhí)行的時候就會報錯,為了避免這種情況,可以有兩種方法解決。
一:設置一個方法,對屬性值進行判斷:
class Student():
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
if __name__ == '__main__': s = Student() s.set_score(value="88") print(s.get_score())
再Student類中,為了避免直接對 _score 屬性操作,我們提供了 get_score 和 set_score 方法,這樣起到了封裝的作用,把一些不想對外公開的屬性隱蔽起來,而只是提供方法給用戶操作,在方法里面,我們可以檢查參數(shù)的合理性等。這樣做沒什么問題,但是我們有更簡單的方式來做這件事。
二:使用propert裝飾器。
class Teacher():
@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__':
t = Teacher()
t.score = 10
print(t.score)
t.score = 20
print(t.score)
在上面,我們給方法 score 加上了 @property,于是我們可以把 score 當成一個屬性來用,此時,又會創(chuàng)建一個新的裝飾器 score.setter,它可以把被裝飾的方法變成屬性來賦值。
另外,我們也不一定要使用 score.setter 這個裝飾器,這時 score 就變成一個只讀屬性了:
class test():
def __init__(self, s1):
self.s = s1
@property
def f1(self):
return self.s
if __name__ == '__main__':
t1 = test(s1=90)
print(t1.f1)
注意:最后面一行的print(t1.f1)不要加括號,print(t1.f1()),要不會報錯'int' object is not callable
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
python+logging+yaml實現(xiàn)日志分割
這篇文章主要為大家詳細介紹了python+logging+yaml實現(xiàn)日志分割,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-07-07
Python MySQLdb模塊連接操作mysql數(shù)據庫實例
這篇文章主要介紹了Python MySQLdb模塊連接操作mysql數(shù)據庫實例,本文直接給出操作mysql代碼實例,包含創(chuàng)建表、插入數(shù)據、插入多條數(shù)據、查詢數(shù)據等內容,需要的朋友可以參考下2015-04-04
Python編程調用百度API實現(xiàn)地理位置經緯度坐標轉換示例
這篇文章主要介紹了Python編程調用百度API來實現(xiàn)地理位置經緯度坐標轉換的示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-10-10
Python線程池thread?pool創(chuàng)建使用及實例代碼分享
這篇文章主要介紹了Python線程池(thread?pool)創(chuàng)建使用及實例代碼分享,文章圍繞主題展開詳細的內容介紹具有一定的參考價值,需要的小伙伴可以參考一下2022-06-06

