Similar structural function calling method implemented in Python

This article describes the Python function call method to achieve similar structure, the paper explains the use of dict and lambda in combination to achieve similar structure function calls, gives an example with no parameters and arguments, a friend in need can refer to
the python dict is easy to use, can customize the key value, and accessed by subscripts, for example:

>>> d = {'key1':'value1',
... 'key2':'value2',
... 'key3':'value3'}
>>> print d['key2']
value2
>>>

lambda expression is also a very practical stuff, for example:

>>> f = lambda x : x**2
>>> print f(2)
4
>>>

Structure similar to a combination of both function calls can be implemented, easy to use, the following examples:
Example 1: with no parameters

 #! /usr/bin/python
 
msgCtrl = "1 : pause\n2 : stop\n3 : restart\nother to quit\n"
 
ctrlMap = {
'1':    lambda : doPause(),
'2':    lambda : doStop(),
'3':    lambda : doRestart()}
 
def doPause():
        print 'do pause'
 
def doStop():
        print 'do stop'
 
def doRestart():
        print 'do restart'
 
if __name__ == '__main__':
        while True:
                print msgCtrl
                cmdCtrl = raw_input('Input : ')
                if not ctrlMap.has_key(cmdCtrl):break
                ctrlMap[cmdCtrl]()

Example Two: parameters

#! /usr/bin/python
 
msgCtrl = "1 : +\n2 : -\n3 : *\nother to quit\n"
 
ctrlMap = {
'1':    lambda x,y : x+y,
'2':    lambda x,y : x-y,
'3':    lambda x,y : x*y}
 
 
if __name__ == '__main__':
        while True:
                print msgCtrl
                cmdCtrl = raw_input('Input : ')
                if not ctrlMap.has_key(cmdCtrl):break
                print ctrlMap[cmdCtrl](10,2),"\n"

Finally, we recommend a very wide python learning resource gathering, [click to enter] , here are my collection before learning experience, study notes, there is a chance of business experience, and calmed down to zero on the basis of information to project combat , we can at the bottom, leave a message, do not know to put forward, we will study together into

Published 34 original articles · won praise 51 · views 40000 +

Guess you like

Origin blog.csdn.net/haoxun10/article/details/104805933