首页 > 解决方案 > 带有“self”的 Python 侦听器方法

问题描述

我可以找到的所有侦听器实现示例都使用没有 的侦听器方法self,如果您想对传递的侦听器方法之外的响应执行某些操作,这似乎无济于事。

这是我正在尝试的:

class A:
    @property
    def command(self):
        return self._command

    @command.setter
    def command(self, command):
        self._command = command
        self._notify_command_observers(command)

    _command_callbacks = []
    def _notify_command_observers(self, command):
        for callback in self._command_callbacks:
            callback(command) #<-- TypeError: function takes 2 positional arguments but 1 were given

    def register_command_callback(self, callback):
        self._command_callbacks.append(callback)

    def receive_command(self, new_command):
        self.command = new_command #<-- an external process will provide this "new_command" variable
class B:
    def use_command(self, command):
        print(command)

    def command_listener(self, command):
        self.use_command(command)

    a = A()
    a.register_command_callback(command_listener)

这会导致上面评论中显示的错误。

如果我self在调用callback()inside_notify_command_observers中使用,则会传递错误的上下文并且use_command()不会找到。

当然我可以删除selfin command_listener(),但我需要访问class B实例中的其他方法和变量。

TL;DR:如何将侦听器方法传递给类实例并在该侦听器中包含传递类的上下文?

- - - - - 编辑 - - - - -

使用@jasonharper 的建议,这有效:

class B:
    def __init__(self):
        self.a = A()
        self.a.register_command_callback(self.command_listener)

    def use_command(self, command):
        print(command)

    def command_listener(self, command):
        self.use_command(command)

标签: pythonlistenerobserver-pattern

解决方案


推荐阅读