Implementing a callback in Python - passing a callable reference to the current function

末鹿安然 提交于 2019-11-27 17:31:48

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>>)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!