Python implements structurally similar function call methods
- 2020-04-02 14:40:24
- OfStack
Python dict is very convenient to use, you can customize the key value, and access through subscripts, as shown in the following example:
>>> d = {'key1':'value1',
... 'key2':'value2',
... 'key3':'value3'}
>>> print d['key2']
value2
>>>
Lambda expressions are also useful, for example:
>>> f = lambda x : x**2
>>> print f(2)
4
>>>
The combination of the two can achieve a similar structure of function calls, it is very convenient to use, as follows:
Example 1: no parameters
#! /usr/bin/python
msgCtrl = "1 : pausen2 : stopn3 : restartnother to quitn"
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 2: take parameters
#! /usr/bin/python
msgCtrl = "1 : +n2 : -n3 : *nother to quitn"
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"