利用CallbackList()实现简单的信号与槽机制
发布时间:2023-12-31 18:05:07
CallbackList是Python中的一个类,用于实现带有信号和槽机制的代码。信号和槽机制是一种常用于软件开发中的通信方式,用于实现不同组件之间的交互和数据传递。CallbackList可以创建一个列表,用于保存需要执行的函数,当信号触发时,槽函数会被调用。
下面是一个使用CallbackList实现信号与槽的例子:
from collections import Callable
class CallbackList:
def __init__(self):
self.callbacks = []
def connect(self, callback):
if isinstance(callback, Callable):
self.callbacks.append(callback)
def disconnect(self, callback):
if callback in self.callbacks:
self.callbacks.remove(callback)
def emit(self, *args, **kwargs):
for callback in self.callbacks:
callback(*args, **kwargs)
# 定义一个槽函数
def slot_func1(arg1, arg2):
print(f"slot_func1 called with arguments: {arg1}, {arg2}")
def slot_func2(arg1, arg2):
print(f"slot_func2 called with arguments: {arg1}, {arg2}")
def slot_func3(arg1, arg2):
print(f"slot_func3 called with arguments: {arg1}, {arg2}")
# 创建一个信号
signal = CallbackList()
# 连接槽函数到信号
signal.connect(slot_func1)
signal.connect(slot_func2)
# 发射信号,调用槽函数
signal.emit("hello", "world")
# 取消连接一个槽函数
signal.disconnect(slot_func1)
# 发射信号,调用槽函数
signal.emit("hello", "world")
# 再连接一个槽函数到信号
signal.connect(slot_func3)
# 发射信号,调用槽函数
signal.emit("hello", "world")
运行以上代码,输出结果如下:
slot_func1 called with arguments: hello, world slot_func2 called with arguments: hello, world slot_func2 called with arguments: hello, world slot_func3 called with arguments: hello, world
在上面的例子中,首先定义了三个槽函数slot_func1,slot_func2和slot_func3用于接收信号触发时传递的参数并进行处理。
然后,我们创建了一个CallbackList实例作为信号,并连接了两个槽函数slot_func1和slot_func2,并使用emit方法发射信号。
当信号被发射时,CallbackList会遍历保存的所有槽函数,并调用它们,将传递的参数传递给槽函数。
在例子中, 次发射信号时,槽函数slot_func1和slot_func2被调用。在第二次发射信号时,只有槽函数slot_func2被调用,因为我们在 个槽函数之后使用disconnect方法取消了与该槽函数的连接。最后一次发射信号时,槽函数slot_func2和slot_func3被调用。
这个例子展示了如何使用CallbackList类实现简单的信号与槽机制,通过连接和断开槽函数来实现槽函数的动态注册和取消,以及使用emit方法发射信号来触发槽函数的执行。它可以帮助我们实现代码的模块化和解耦,从而更好地管理和维护我们的代码。
