類里面秋麸,@property廣泛應(yīng)用在類的定義中恼琼,可以讓調(diào)用者寫出簡(jiǎn)短的代碼,同時(shí)保證對(duì)參數(shù)進(jìn)行必要的檢查拆讯,這樣脂男,程序運(yùn)行時(shí)就減少了出錯(cuò)的可能性。
@property? #getting
@xxx.setter?? #setting
關(guān)于只讀屬性:只定義getter方法种呐,不定義setter方法就是一個(gè)只讀屬性宰翅。
關(guān)于,函數(shù)命名爽室,和變量:
1 getting和setting函數(shù)的函數(shù)名相同
2 self._width 或者self.__width汁讼,一定要有下劃線(不確定,以后再確定阔墩。但無下劃線會(huì)報(bào)錯(cuò)
例子:
請(qǐng)利用@property給一個(gè)Screen對(duì)象加上width和height屬性嘿架,以及一個(gè)只讀屬性resolution:
代碼:
class Screen(object):
? ? @property
? ? def width(self):
? ? ? ? return self._width
? ? @width.setter
? ? def width(self,value):
? ? ? ? self._width=value
? ? @property
? ? def height(self):
? ? ? ? return self._height
? ? @height.setter
? ? def height(self,value):
? ? ? ? self._height=value
? ? @property
? ? def resolution(self):
? ? ? ? return self._width * self._height
#測(cè)試
s = Screen()
s.width = 1024
s.height = 768
print('resolution =', s.resolution)
if s.resolution == 786432:
? ? print('測(cè)試通過!')
else:
? ? print('測(cè)試失敗!')