Python學習筆記(1) ——property的使用
阿新 • • 發佈:2018-11-01
@property的使用
Python內建的@property裝飾器就是負責把一個方法變成屬性呼叫的。
下面我將用一個簡單的例子來說明@property的使用。
程式碼實現如下:
class Screen(object): @property def width(self): return self._width @width.setter def width(self, width): self._width =width @property def height(self): return self._height @height.setter def height(self, height): self._height = height @property def resolution(self): return self._height*self._width
首先我們來看一下要求,它說要使用@property新增屬性,並且還需要設定一個只讀屬性。
- 我們需要使用@property,把getter方法變成一個屬性,此時,@property本身又建立了另一個裝飾器@width.setter,負責把一個setter方法變成屬性賦值。
- 對resolution,我們只定義get方法,不定義set方法,就是一個只讀屬性。