Python dynamic function names

前端 未结 8 1334
星月不相逢
星月不相逢 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:00

    you might find getattr useful, I guess

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

    it seams that you can use getattr in a slightly different (in my opinion more elegant way)

    import math
    getattr(math, 'sin')(1)
    

    or if function is imported like below

    from math import sin
    

    sin is now in namespace so you can call it by

    vars()['sin'](1)
    
    0 讨论(0)
  • 2020-12-29 14:02

    Look at this: getattra as a function dispatcher

    0 讨论(0)
  • 2020-12-29 14:03

    Some improvement to SilentGhost's answer:

    globals()[status.lower()](*args, **kwargs)
    

    if you want to call the function defined in the current module.

    Though it looks ugly. I'd use the solution with dictionary.

    0 讨论(0)
  • 2020-12-29 14:03

    I encountered the same problem previously. Have a look at this question, I think its what you are looking for.

    Dictionary or If Statements

    Hope this is helpful

    Eef

    0 讨论(0)
  • 2020-12-29 14:05

    some change from previous one:

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