问题描述
我想在 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)
位?
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 中实现回调 - 传递对当前函数的可调用引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!