在装饰器中使用部分时自我丢失

Gon*_*dez 3 python python-3.x python-decorators

我正在尝试从使用另一个类的装饰器的类编写方法。问题是我需要存储在包含装饰器(ClassWithDecorator.decorator_param)的类中的信息。为了实现这一点,我使用部分注入 self 作为第一个参数,但是当我这样做时,使用装饰器的类中的 self 不知何故“丢失了”,最终我得到了一个错误。请注意,如果我partial()从中删除my_decorator()并且“self”将正确存储在*args.

查看代码示例:

from functools import partial


class ClassWithDecorator:
    def __init__(self):
        self.decorator_param = "PARAM"

    def my_decorator(self, decorated_func):
        def my_callable(ClassWithDecorator_instance, *args, **kwargs):
            # Do something with decorator_param
            print(ClassWithDecorator_instance.decorator_param)
            return decorated_func(*args, **kwargs)

        return partial(my_callable, self)


decorator_instance = ClassWithDecorator()


class WillCallDecorator:
    def __init__(self):
        self.other_param = "WillCallDecorator variable"

    @decorator_instance.my_decorator
    def decorated_method(self):
        pass


WillCallDecorator().decorated_method()
Run Code Online (Sandbox Code Playgroud)

我得到

PARAM
Traceback (most recent call last):
  File "****/decorator.py", line 32, in <module>
    WillCallDecorator().decorated_method()
  File "****/decorator.py", line 12, in my_callable
    return decorated_func(*args, **kwargs)
TypeError: decorated_method() missing 1 required positional argument: 'self'
Run Code Online (Sandbox Code Playgroud)

如何将对应的 self 传递到WillCallDecorator()intodecorated_method()但同时将信息从它自己的类传递到my_callable()

Ene*_*gya 5

似乎您可能想要使用partialmethod而不是partial

从文档:

class functools.partialmethod(func, /, *args, **keywords)

当 func 是非描述符可调用时,会动态创建适当的绑定方法。当用作方法时,这就像一个普通的 Python 函数:self 参数将作为第一个位置参数插入,甚至在提供给 partialmethod 构造函数的 args 和关键字之前。