python - 在装饰器中使用 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()
?
解决方案
看来您可能想要使用partialmethod
而不是partial
:
从文档:
class functools.partialmethod(func, /, *args, **keywords)
当 func 是非描述符可调用时,会动态创建适当的绑定方法。当用作方法时,它的行为类似于普通的 Python 函数:self 参数将作为第一个位置参数插入,甚至在提供给 partialmethod 构造函数的参数和关键字之前。
推荐阅读
- python - Python/Pytest:pytest_sessionstart() 中的修补函数未返回预期值
- python - 赋值前引用的局部变量索引
- angular - Angular 11 - 类型 MatDialogRef 没有“emod”属性
- python - TELEPOT 尝试回调查询以发送消息时未找到聊天时不断收到错误 400
- stata - 基于多个条件的新变量(Stata)
- sse - 如何在有或没有 SIMD 内在函数的情况下从 Zig 构建和链接到 CGLM
- ios - 如何从一个目标调用函数到另一个目标ios swift xcode
- android - 使用 adb 从 Android 获取即时电流 il 毫安
- javascript - 过滤的 GeoJson 几何在 Leaflet 上无法正常工作
- ios - 未调用委托函数