Using a dictionary to select function to execute

前端 未结 10 2080
走了就别回头了
走了就别回头了 2020-11-27 13:05

I am trying to use functional programming to create a dictionary containing a key and a function to execute:

myDict={}
myItems=(\"P1\",\"P2\",\"P3\",....\"         


        
10条回答
  •  离开以前
    2020-11-27 13:52

    Simplify, simplify, simplify:

    def p1(args):
        whatever
    
    def p2(more args):
        whatever
    
    myDict = {
        "P1": p1,
        "P2": p2,
        ...
        "Pn": pn
    }
    
    def myMain(name):
        myDict[name]()
    

    That's all you need.


    You might consider the use of dict.get with a callable default if name refers to an invalid function—

    def myMain(name):
        myDict.get(name, lambda: 'Invalid')()
    

    (Picked this neat trick up from Martijn Pieters)

提交回复
热议问题