Member function decorator and self argument
成员函数上装饰器的以下最小示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 | def wrap_function(func): def wrapper(*args, **kwargs): print(args) print(kwargs) return wrapper class Foo: @wrap_function def mem_fun(self, msg): pass foo = Foo() foo.mem_fun('hi') |
输出:
1 2 | (<__main__.Foo object at 0x7fb294939898>, 'hi') {} |
因此,
但是,当使用包装类时:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class WrappedFunction: def __init__(self, func): self._func = func def __call__(self, *args, **kwargs): print(args) print(kwargs) def wrap_function(func): return WrappedFunction(func) class Foo: @wrap_function def mem_fun(self, msg): pass foo = Foo() foo.mem_fun('hi') |
输出是:
1 2 | ('hi',) {} |
因此,引用
我怎样才能到达那里?
*你*参考丢给你bounded审by wrapping的功能逻辑(但不是*审redirecting)和它的审级美元的那一点,审级的自己
你要打电话到wrapped包装的功能和通过
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class WrappedFunction(object): def __call__(self, func): def wrapper(*args, **kwargs): print(args) print(kwargs) # NOTE: `WrappedFunction` instance is available in `self` return wrapper class Foo: @WrappedFunction() # wrap directly, without an intermediary def mem_fun(self, msg): pass foo = Foo() foo.mem_fun('hi') # (<__main__.Foo object at 0x000001A2216CDBA8>, 'hi') # {} |
赛特笠,但这可能是唯一的解决办法在你需要它在
1 2 3 4 5 | def wrap_function(func): def wrapper(*args, **kwargs): x = WrappedFunction(func) x(*args, **kwargs) return wrapper |