Using a dictionary to select function to execute

前端 未结 10 2104
走了就别回头了
走了就别回头了 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:56

    Often classes are used to enclose methods and following is the extension for answers above with default method in case the method is not found.

    class P:
    
         def p1(self):
             print('Start')
    
         def p2(self):
             print('Help')
    
         def ps(self):
             print('Settings')
    
         def d(self):
             print('Default function')
    
         myDict = {
             "start": p1,
             "help": p2,
             "settings": ps
         }
    
         def call_it(self):
             name = 'start'
             f = lambda self, x : self.myDict.get(x, lambda x : self.d())(self)
             f(self, name)
    
    
     p = P()
     p.call_it()
    

提交回复
热议问题