Python dynamic function names

前端 未结 8 1335
星月不相逢
星月不相逢 2020-12-29 13:54

I\'m looking for a better way to call functions based on a variable in Python vs using if/else statements like below. Each status code has a corresponding function



        
相关标签:
8条回答
  • 2020-12-29 14:08

    assuming that these functions belong to some module:

    import module
    return getattr(module, status.lower()).__call__(*args, **kwargs)
    
    0 讨论(0)
  • 2020-12-29 14:24

    The canonical way to do this is to use a dictionary to emulate switch or if/elif. You will find several questions to similar problems here on SO.

    Put your functions into a dictionary with your status codes as keys:

    funcs = {
        'CONNECT': connect,
        'RAWFEED': rawfeed,
        'RAWCONFIG' : rawconfig,
        'TESTFEED': testfeed
    }
    funcs[status](*args, **kwargs)
    
    0 讨论(0)
提交回复
热议问题