1. 程式人生 > 實用技巧 >@property裝飾器

@property裝飾器

一、概述

  類中的屬性可以直接訪問和賦值,這為類的使用者提供了方便,但也帶來了問題:類的使用者可能會給一個屬性賦上超出有效範圍的值。

  為了解決這個問題,Python提供了@property裝飾器,可以將類中屬性的訪問和賦值操作自動轉為方法呼叫,這樣可以在方法中對屬性值的取值範圍做一些條件限定。   直接使用@property就可以定義一個用於獲取屬性值的方法(即getter)。   如果要定義一個設定屬性值的方法(setter),則需要使用名字“@屬性名.setter”的裝飾器。   如果一個屬性只有用於獲取屬性值的getter方法,而沒有用於設定屬性值的setter方法,則該屬性是一個只讀屬性,只允許讀取該屬性的值、而不能設定該屬性的值。 二、例:通過@property裝飾器使得學生成績的取值範圍必須在0~100之間。
import
datetime class Student: #定義Student類 @property def score(self): #用@property裝飾器定義一個用於獲取score值的方法 return self._score #注意:在類的setter和getter方法中使用self訪問屬性時,需要在屬性名前加上 下劃線,否則系統會因不斷遞迴呼叫而報錯。 @score.setter def score(self, score): #用score.setter定義一個用於設定score值的方法 if score<0 or
score>100: #不符合0~100的限定條件 print('成績必須在0~100之間!') else: self._score=score @property def age(self): #用@property裝飾器定義一個用於獲取age值的方法 return datetime.datetime.now().year-self.birthyear if __name__=='__main__': stu=Student() #建立Student類物件stu stu.score=80 #
將stu物件的score屬性賦值為80 stu.birthyear=2000 #將stu物件的birthyear屬性賦值為2000 print('年齡:%d,成績:%d'%(stu.age,stu.score)) #stu.age=19 #取消前面的註釋符則會報錯 stu.score=105 #將stu物件的score屬性賦值為105 print('年齡:%d,成績:%d'%(stu.age,stu.score))
成績必須在0~100之間! 年齡:18,成績:80