python - 带有“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()
不会找到。
当然我可以删除self
in 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)
解决方案
推荐阅读
- spring-batch - Spring Batch中如何基于configruaiton动态形成XML
- php - 如何使用codeigniter上传超过1mb的文件
- django - 自定义 allauth django 项目的 email_confirmation_message.txt 会出错怎么办?
- java - IDEA 中的 Maven 错误:模块“quickStart”所需的 Maven 项目配置不可用
- excel - 如何在xssfworkbook的同一单元格中获取图像和数据
- sql - SQL For循环在列中查找空值,而不是空值
- linux - AMD Epyc (Zen 2) 禁用硬件预取 L2
- serial-port - 串行端口环回测试如何在内部/下面工作?
- java - 与 Beam 中的运行器依赖项冲突
- botframework - Microsoft Teams APP Studio - 在清单编辑器中找不到消息端点字段