裝飾器(decorator)可以給函數(shù)動態(tài)加上功能,對于類的方法,裝飾器一樣起作用。Python內(nèi)置的@property裝飾器就是負(fù)責(zé)把一個方法變成屬性調(diào)用的:
下面寫一個例子,如有不懂的同學(xué)可以聯(lián)系我郵箱
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__='byx54192@gmail.com'
class Student(object):
@property #將birth 轉(zhuǎn)換為屬性,外部可是直接s.birth訪問
def birth(self):
return self._birth
@birth.setter #@property本身又創(chuàng)建了另一個裝飾器@score.setter,負(fù)責(zé)把一個setter方法變成屬性賦值
def birth(self, value):
if value>0 and value<100:
self._birth = value
else:
raise ValueError('birth must between 0~100')
@property #將age方法轉(zhuǎn)換為屬性,外部調(diào)用時,可以用s.age訪問。
def age(self):
return 2015 - self._birth
s= Student()
s.birth=10
print(s.age)
print(s.birth)
練習(xí)
請利用@property給一個Screen對象加上width和height屬性,以及一個只讀屬性resolution:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__='byx54192@gmail.com'
class Screen(object):
@property
def width(self):
return self._width
@width.setter
def width(self,value):
if value!=768:
return 0
self._width=value
@property
def height(self):
return self._height
@height.setter
def height(self,value):
if value!=1024:
return 0
self._height=value
@property
def resolution(self):
return self._width*self._height
s=Screen()
s.width=768
s.height=1024
print('resolution=',s.resolution)
if s.resolution == 786432:
print('測試通過!')
else:
print('測試失敗!')

圖片發(fā)自簡書App