装饰器
@decoratory
def f(x):
pass
相当于f=decoratory(f)
一个一般的装饰函数如下:
import time def performance(f): def fn(*arg,**kw): t1=time.time() r=f(*arg,**kw) t2=time.time() print 'call %s() in %fs' %(f.__name__,t2-t1) return r return fn @performance def factorial(n): return reduce(lambda x,y: x*y, range(1, n+1)) print factorial(10)
带参数的装饰器:
import time def performance(unit): def decoration(f): def fn(*args,**kw): t1=time.time() r=f(*args,**kw) t2=time.time() t=t2-t1 if unit=='ms': t=(t2-t1)*1000 print 'call %s() in %f%s' %(f.__name__,t,unit) return r return fn return decoration @performance('ms') def factorial(n): return reduce(lambda x,y: x*y, range(1, n+1)) print factorial(10)
@property作为一个装饰器使用,相当于调用property(getx,setx,delx,doc),它会把get函数,set函数和del函数重新装饰后返回,
class Student(object): def __init__(self, name, score): self.name = name self.__score = score @property def score(self): return self.__score @score.setter def score(self, score): if score < 0 or score > 100: raise ValueError('invalid score') self.__score = score @property def grade(self): if self.score<60: return 'C' if self.score<80: return 'B' return 'A'
@score.setter是副产品,定义完get函数后,要定义setter和del就必须利用副产品,同时三个函数名必须相同。c是类的实例,则c.score调用get,c.score=value调用set,del c.score删除函数