函数装饰器提供了一种方式,替函数明确了特定的运算模式,也就是将函数包裹了另一层,在另一函数的逻辑内实现
静态方法的实现可以用如下的装饰器语法编写
class C:
@staticmethod
def meth():
........
装饰器实现的例子:
class tracer:
def __init__(self,func):
self.calls=0
self.func=func
#----------------------------------------------------------------------
def __call__(self,*args):
"""
__call__"""
self.calls+=1
print 'calls %s to %s ' % (self.calls,self.func.__name__)
self.func(*args)
@tracer
def spam(a,b,c):
print a,b,c
spam(1,2,3)
spam('q','b','c')
spam(4,6,5)
执行结果:
calls 1 to spam
1 2 3
calls 2 to spam
q b c
calls 3 to spam
4 6 5