简体   繁体   English

Python:带有装饰器的函数__qualname__

[英]Python: __qualname__ of function with decorator

I'm using a Decorator (class) in an Instance method of another class, like this: 我在另一个类的Instance方法中使用了Decorator(类),如下所示:

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__)

Now, when I print out self.sayHello.__qualname__ it prints decorator_with_arguments.__call__.<locals>.wrapped_f 现在,当我打印出self.sayHello.__qualname__它会打印decorator_with_arguments.__call__.<locals>.wrapped_f

Is there any way to override this? 有没有办法改写这个? I want to see Lol.sayHello ( qualname of my original function) in here. 我想在这里看到Lol.sayHello (我原来的功能的名字 )。

I tried overriding the @property __qualname__ of __call__ (with a static string); 我试图重写@property __qualname____call__ (用静态字符串); didn't work. 没用。

You can simply copy the __qualname__ attribute across to your wrapped_f wrapper function ; 您只需将__qualname__属性复制到wrapped_f包装函数即可 ; it is this function that is returned when the decorator is applied, after all. 毕竟,在应用装饰器时会返回此函数。

You could use the @functools.wraps() decorator to do this for you, together with other attributes of note: 您可以使用@functools.wraps()装饰器为您执行此操作,以及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

The @wraps(f) decorator there copies the relevant attributes from f onto wrapped_f , including __qualname__ : @wraps(f)装饰器将相关属性从f复制到wrapped_f ,包括__qualname__

>>> Lol.sayHello.__qualname__
'Lol.sayHello'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM