简体   繁体   中英

Python pseudo callback function

I have my 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

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. I have other pieces to the Application class that listen to a usb message and invoke 'receivedMessage'

Thanks

You could pass the foo function to your 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.

#!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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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