简体   繁体   English

Python 伪回调 function

[英]Python pseudo callback function

I have my main.py我有我的 main.py

import application

def foo(args):
    print("Invoked!")

def main():
    app = application.Application()
    # here i want to connect app.receivedMessage to foo

and my application.py和我的 application.py

class Application:
    def __init__(self):
        pass

    def receivedMessage(self, args):
        # somehow call foo(args)

Basically how can I call foo and pass the args when receivedMessage is called.基本上我如何调用 foo 并在调用 receivedMessage 时传递参数。 I have other pieces to the Application class that listen to a usb message and invoke 'receivedMessage'我在应用程序 class 中还有其他部分,它们侦听 usb 消息并调用“receivedMessage”

Thanks谢谢

You could pass the foo function to your Application object:您可以将foo function 传递给您的Application object:

 class Application:
    def __init__(self, foo):
        self.foo = foo

    def receivedMessage(self, args):
        self.foo(args)

Passing the function as an argument works fine too.将 function 作为参数传递也可以。

#!python3
class Application:
    def __init__(self):
        pass
    def receivedMessage(self,args,**kwargs):
        if kwargs and kwargs['foo']:
            foo=kwargs['foo']
            foo(args)

def foo(args):
    print('Invoked')
if __name__=='__main__':
    app = Application()
    app.receivedMessage("haha", foo=foo) # works
    app.receivedMessage("haha") # doesn't raise error

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM