如何在Python中传递和运行回调方法

如何在Python中传递和运行回调方法,第1张

如何在Python中传递和运行回调方法

除非具有对管理器的引用,否则该线程无法调用管理器。最简单的方法是管理器在实例化时将其提供给线程。

class Manager(object):    def new_thread(self):        return MyThread(parent=self)    def on_thread_finished(self, thread, data):        print thread, dataclass MyThread(Thread):    def __init__(self, parent=None):        self.parent = parent        super(MyThread, self).__init__()    def run(self):        # ...        self.parent and self.parent.on_thread_finished(self, 42)mgr    = Manager()thread = mgr.new_thread()thread.start()

如果您希望能够将任意函数或方法分配为回调,而不是存储对管理器对象的引用,则由于方法包装器等原因,这将带来一些问题。设计回调很困难,因此它需要引用管理器
线程。我做了一段时间,没有提出任何我认为有用或优雅的东西。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5673613.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存