Python WeakRef.WeakMethod 传递参数

Python WeakRef.WeakMethod pass arguments

目前我正在尝试使用 Command Pattern 创建一个 class。 对于动作 class,我有类似的东西:

class SimpleCommand(Command):
    """
    Some commands can implement simple operations on their own.
    """
    def __init__(self, callable: Callable) -> None:
        self._callable = callable

    def execute(self) -> None:
        self._callable()

为了防止内存泄漏,我打算维护对可调用方法的弱引用。有什么方法可以使用 weakref.WeakMethod 并传递多个参数吗?我尝试使用 functools.partial,但这会导致 weak 方法被视为已死。

我最后向 SimpleCommand 添加了一些额外的参数 class 以允许将参数传递给 WeakMethod。

class SimpleCommand(Command):
"""
Some commands can implement simple operations on their own.
"""
def __init__(self, callable: Callable, *callable_args, **callable_kwargs) -> None:
    self._callable = weakref.WeakMethod(callable)
    self._callable_args = callable_args
    self._callable_kwargs = callable_kwargs

def execute(self) -> None:
    if self._callable() is not None:
        self._callable()(*self._callable_args, **self._callable_kwargs)