1 使用__call__(self,[..)方法将类变成装饰器
这里我就用一个例子和执行图来解释了
class Describer(object): def __init__(self, name): self.name = name def __call__(self, func): # func 是 Foo().foo print 'im Describer call' def inner(foo_self, *args): # foo_self是Foo()对象 print foo_self.name return func(foo_self, *args) return inner class Foo(object): def __init__(self): self.name = 'www' @Describer('zhn') # 相当于 temp = Describer(__init__); inner = temp__call__(foo); func_result = inner(foo_self, *args) def foo(self): return 'im Foo instance foo' f = Foo() print f.foo()
result:
im Describer call
www
im Foo instance foo
f.foo() 相当于
temp = Describer(‘zhn’);
inner = temp__call__(foo);
func_result = inner(foo_self, *args)
程序执行图
2 使用静态方法或者类方法将类的方法变为装饰器
class Des(object): @staticmethod def des_func(sth): def middle(func): def inner(obj, *args): print 'first we talk %s' % sth print 'obj is %s' % obj.name return func(obj, *args) return inner return middle class Foo(object): def __init__(self): self.name = 'wwww' @Des.des_func('pig') def foo_func(self): print 'the func is foo_func' return foo = Foo() foo.foo_func()
# out: # first we talk pig # obj is wwww # the func is foo_func
参考
Python Decorators II: Decorator Arguments by Bruce Eckel 地址