Python:带有修饰符的函数的__qualname__ [英] Python: __qualname__ of function with decorator
问题描述
我正在另一个类的Instance方法中使用Decorator(类),如下所示:
I'm using a Decorator (class) in an Instance method of another class, like this:
class decorator_with_arguments(object):
def __init__(self, arg1=0, arg2=0, arg3=0):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
def __call__(self, f):
print("Inside __call__()")
def wrapped_f(*args):
print(f.__qualname__)
f(*args)
return wrapped_f
class Lol:
@decorator_with_arguments("hello")
def sayHello(self,a1, a2, a3, a4):
print(self.sayHello.__qualname__)
现在,当我打印出 self.sayHello .__ qualname __
时,它会打印 decorator_with_arguments .__ call __.< locals> .wrapped_f
Now, when I print out self.sayHello.__qualname__
it prints decorator_with_arguments.__call__.<locals>.wrapped_f
有什么办法可以覆盖这个?我想在这里看到 Lol.sayHello
(我的原始函数的质量名称).
Is there any way to override this? I want to see Lol.sayHello
(qualname of my original function) in here.
我尝试覆盖 __ call __
的 @property
__ qualname __
(使用静态字符串);没用.
I tried overriding the @property
__qualname__
of __call__
(with a static string); didn't work.
推荐答案
您只需将 __ qualname __
属性复制到您的 wrapped_f
包装函数中>;毕竟,应用装饰器时将返回此函数.
You can simply copy the __qualname__
attribute across to your wrapped_f
wrapper function; it is this function that is returned when the decorator is applied, after all.
您可以使用 @ functools.wraps()
装饰器为您完成此操作,以及note的其他属性:
You could use the @functools.wraps()
decorator to do this for you, together with other attributes of note:
from functools import wraps
class decorator_with_arguments(object):
def __init__(self, arg1=0, arg2=0, arg3=0):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
def __call__(self, f):
print("Inside __call__()")
@wraps(f)
def wrapped_f(*args):
print(f.__qualname__)
f(*args)
return wrapped_f
那里的 @wraps(f)
装饰器将相关属性从 f
复制到 wrapped_f
,包括 __ qualname __
:
The @wraps(f)
decorator there copies the relevant attributes from f
onto wrapped_f
, including __qualname__
:
>>> Lol.sayHello.__qualname__
'Lol.sayHello'
这篇关于Python:带有修饰符的函数的__qualname__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!