python - 在 Python 中注册要在事件上调用的函数

标签 python events callback function-pointers

我想编写一个函数,该函数将在事件发生后调用,但前提是用户已注册该函数。

例如

#Defination
def fnBookUber(objUser):
    print 'Inside fbBookUber()'

#calling
def myEvent(objUser):
    print 'This event has fired'
    # This function will fill objUser too
    fnBookUber(objUser)

#Registeration
fnRegisterRideBooking(fnBookUber)

我知道我的解释有点奇怪,但我不知道如何在 python 中完成此操作,尽管我强烈认为在 python 中一定有很多方法可以做到这一点。 另外,我认为这可以通过在 C++ 中使用函数指针和在 C# 中使用委托(delegate)来实现。

最佳答案

这是注册和调用事件的一种方法。

import types

#Callback
def fnBookUber(objUser):
    print('Inside fbBookUber()')

class myEvent:
    def __init__(self):
        self.callbacks = list()

    def registerCallback(self, callback: types.FunctionType):
        self.callbacks.append(callback)

    def call(self, objUser):
        print('This event has fired')

        for callback in self.callbacks:
            callback(objUser)

if __name__ == "__main__":
    myEvent = myEvent()

    #Registration
    myEvent.registerCallback(fnBookUber)

    #Calling/Firing the event
    myEvent.call()

也可以直接传递函数,如

def myEvent(objUser, callback):
    print('This event has fired')
    callback(objUser)

并将该事件称为:

myEvent(objUser, fnBookUber)

这比前一个不太灵活。

关于python - 在 Python 中注册要在事件上调用的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58925648/

相关文章:

python - 如何使用mysql在数据库端声明默认高精度日期时间default + onupdate

python - 从 Bokeh Donut 对象获取组件

Javascript:如何跟踪 div 的绝对位置(顶部/左侧)?

javascript - jQuery.post动态数据回调函数

javascript - webkitTransitionEnd 在重绘/回流之前被触发

python - virtualenv 使用源代码库

Python ElementTree 支持解析未知 XML 实体?

MySQL Event 在存储的日期和时间添加预订

events - 在 f# 中创建 Event.create?

c++ - 这个回调有什么问题?