python3.6中@property裝飾器的使用方法示例
本文實例講述了python3.6中@property裝飾器的使用方法。分享給大家供大家參考,具體如下:
1、@property裝飾器的使用場景簡單記錄如下:
- 負責把一個方法變成屬性調用;
- 可以把一個getter方法變成屬性,
@property本身又創(chuàng)建了另一個裝飾器@score.setter,負責把一個setter方法變成屬性賦值; - 只定義getter方法,不定義setter方法就是一個只讀屬性
2、通過一個例子來加深對@property裝飾器的理解:利用@property給一個Screen對象加上width和height屬性,以及一個只讀屬性resolution。
代碼實現(xiàn)如下:
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,values):
self._height = values
@property
def resolution(self):
return self._width * self._height
s = Screen()
s.width = 1024
s.height = 768
print('resolution = ',s.resolution)
運行結果:
resolution = 786432
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python面向對象程序設計入門與進階教程》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設計有所幫助。

