您不需要弄乱描述符。在
__call__()方法内部创建包装函数并返回它就足够了。根据上下文,标准Python函数始终可以充当方法或函数:
class MyDecorator(object): def __init__(self, argument): self.arg = argument def __call__(self, fn): @functools.wraps(fn) def decorated(*args, **kwargs): print "In my decorator before call, with arg %s" % self.arg fn(*args, **kwargs) print "In my decorator after call, with arg %s" % self.arg return decorated
关于使用这种装饰器时发生的情况的一些解释:
@MyDecorator("some other func!")def some_other_function(): print "in some other function!"第一行创建的实例
MyDecorator并将其
"some otherfunc!"作为参数传递给
__init__()。我们称这个实例
my_decorator。接下来,创建未修饰的函数对象(我们称其为“对象”)
bare_func并将其传递给装饰器实例,然后
my_decorator(bare_func)执行该对象。这将调用
MyDecorator.__call__(),这将创建并返回包装器函数。最后,将此包装函数分配给名称
some_other_function。



