【问题标题】:Python WeakRef.WeakMethod pass argumentsPython WeakRef.WeakMethod 传递参数
【发布时间】:2019-12-10 08:28:21
【问题描述】:

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

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,但这会导致弱方法被视为已死。

【问题讨论】:

    标签: python weak-references command-pattern


    【解决方案1】:

    我最终向 SimpleCommand 类添加了一些额外的参数,以允许将参数传递给 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)
    

    【讨论】:

      猜你喜欢
      • 2019-05-21
      • 2012-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-08
      • 2016-02-08
      • 1970-01-01
      • 2016-09-09
      相关资源
      最近更新 更多