在Python中实现回调 - 将可调用的引用传递给当前函数 [英] Implementing a callback in Python - passing a callable reference to the current function

查看:483
本文介绍了在Python中实现回调 - 将可调用的引用传递给当前函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Python中为几个工作者实现 Observable 模式,并遇到了以下有用的代码段:

I want to implement the Observable pattern in Python for a couple of workers, and came across this helpful snippet:

class Event(object):
    pass

class Observable(object):
    def __init__(self):
        self.callbacks = []
    def subscribe(self, callback):
        self.callbacks.append(callback)
    def fire(self, **attrs):
        e = Event()
        e.source = self
        for k, v in attrs.iteritems():
            setattr(e, k, v)
        for fn in self.callbacks:
            fn(e)

源:这里

据我所知,为了 subscribe ,我需要传递一个回调给在 fire 上调用的函数。如果调用函数是一个 class 方法,大概我可以使用 self ,但在没有这个 - 我可以直接得到一个回调,可以用于 self.callbacks.append(callback) bit?

As i understand it, in order to subscribe, I would need to pass a callback to the function that is going to be called on fire. If the calling function was a class method, presumably I could have used self, but in the absence of this - how could I directly get a callback that can be useful for the self.callbacks.append(callback) bit?

推荐答案

任何定义的函数都可以通过简单的使用它的名字来传递,而不用在你要用来调用它的那一端添加()

Any defined function can be passed by simply using its name, without adding the () on the end that you would use to invoke it:

def my_callback_func(event):
    # do stuff

o = Observable()
o.subscribe(my_callback_func)






其他示例用法:


Other example usages:

class CallbackHandler(object):
    @staticmethod
    def static_handler(event):
        # do stuff

    def instance_handler(self, event):
        # do stuff

o = Observable()

# static methods are referenced as <class>.<method>
o.subscribe(CallbackHandler.static_handler)

c = CallbackHandler()
# instance methods are <class instance>.<method>
o.subscribe(c.instance_handler)

# You can even pass lambda functions
o.subscribe(lambda event: <<something involving event>>)

这篇关于在Python中实现回调 - 将可调用的引用传递给当前函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆