【发布时间】:2020-04-12 23:19:05
【问题描述】:
我正在尝试从一个使用另一个类的装饰器的类中编写一个方法。问题是我需要存储在包含装饰器(ClassWithDecorator.decorator_param)的类中的信息。为了实现这一点,我使用部分注入 self 作为第一个参数,但是当我这样做时,使用装饰器的类中的 self 以某种方式“迷路了”,我最终得到了一个错误。请注意,如果我从my_decorator() 中删除partial(),则不会发生这种情况,并且“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'
如何将WillCallDecorator()对应的self传递给decorated_method(),同时将自己类中的信息传递给my_callable()?
【问题讨论】:
-
这能回答你的问题吗? Decorators with parameters?
-
但是为什么
partial()会从参数中删除 self 呢? -
装饰器始终在需要明确接收自身作为参数的未绑定方法上工作。
-
你为什么要使用
partial?装饰器可以直接作为作用域变量访问self。
标签: python python-3.x python-decorators