is there any way to run a other function after a function run finish?

前端 未结 2 1879
慢半拍i
慢半拍i 2021-01-17 05:48
def foo():
    pass

def bar():
    print \'good bay\'

two function like blow and now i want to run bar function after foo run finish

is th

2条回答
  •  梦毁少年i
    2021-01-17 06:38

    This is what decorators are for. This decorator, used on foo with bar as an argument will will run bar after foo and still return foos result. It will work on functions with any number of arguments.

    def run_before(lastfunc, *args1, **kwargs1):
        def run(func):
            def wrapped_func(*args, **kwargs):
                try:
                    result = func(*args, **kwargs)
                except:
                    result = None
                finally:
                    lastfunc(*args1, **kwargs1)
                    return result
            return wrapped_func
        return run
    
    def bar():
        print 'goodby'
    
    @run_before(bar)
    def foo():
        print "hello"
    
    foo()
    

    Edit: Added error handling. Thanks @Björn

提交回复
热议问题