下面是我尝试将MyClass.func
from(self, a, b, c)
的签名更改为的 MWE (self, x, y, z)
。从输出中可以看出,change_sig
装饰器适用于函数,也适用于绑定方法MyClass().func
,但在未绑定方法上失败。当我将一个可调用属性分配给一个阻止它工作的类时,是否有某种魔法在幕后发生?
MWE:
import wrapt
import inspect
def change_sig(func):
adapter = '(self, x, y, z)'
@wrapt.decorator(adapter=adapter)
def wrapper(wrapped, instance, args, kwargs):
pass
wrapped_func = wrapper(func)
return wrapped_func
@change_sig
def func(self, a, b, c):
pass
class MyClass:
@change_sig
def func(self, a, b, c):
pass
print('inspect.signature(func):', inspect.signature(func))
print('inspect.signature(MyClass.func):', inspect.signature(MyClass.func))
print('inspect.signature(MyClass().func):', inspect.signature(MyClass().func))
print('inspect.signature(change_sig(MyClass.func)):', inspect.signature(change_sig(MyClass.func)))
MyClass.wrapped_func = change_sig(MyClass.func)
print('inspect.signature(MyClass.wrapped_func):', inspect.signature(MyClass.wrapped_func))
输出:
inspect.signature(func): (self, x, y, z)
inspect.signature(MyClass.func): (self, a, b, c)
inspect.signature(MyClass().func): (x, y, z)
inspect.signature(change_sig(MyClass.func)): (self, x, y, z)
inspect.signature(MyClass.wrapped_func): (self, a, b, c)