在 Python 中实现回调 - 传递对当前函数的可调用引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4689984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Implementing a callback in Python - passing a callable reference to the current function
提问by malangi
I want to implement the Observablepattern in Python for a couple of workers, and came across this helpful snippet:
我想Observable在 Python 中为几个工人实现该模式,并遇到了这个有用的片段:
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)
Source: Here
来源:这里
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 classmethod, 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?
据我了解,为了subscribe,我需要将回调传递给将要调用的函数fire。如果调用函数是一个class方法,大概我可以使用self,但是在没有这个的情况下 - 我怎么能直接获得一个对这个self.callbacks.append(callback)位有用的回调?
采纳答案by Amber
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>>)

