首页 > 解决方案 > 在装饰器中使用 partial 时自我丢失

问题描述

我正在尝试从一个使用另一个类的装饰器的类中编写一个方法。问题是我需要存储在包含装饰器(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()

我明白了

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'

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

标签: pythonpython-3.xpython-decorators

解决方案


看来您可能想要使用partialmethod而不是partial

从文档:

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

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


推荐阅读