Python implements function calling methods with similar structures.

Source: Internet
Author: User

Python implements function calling methods with similar structures.

Python dict is easy to use. You can customize the key value and access it through subscript, for example:
Copy codeThe Code is as follows:
>>> D = {'key1': 'value1 ',
... 'Key2': 'value2 ',
... 'Key3': 'value3 '}
>>> Print d ['key2']
Value2
>>>

Lambda expressions are also very useful, for example:
Copy codeThe Code is as follows:
>>> F = lambda x: x ** 2
>>> Print f (2)
4
>>>

The combination of the two can implement function calls with similar structures, which is convenient to use. The example is as follows:

Example 1: Without Parameters
Copy codeThe Code is as follows:
#! /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 stopped'
 
Def doRestart ():
Print 'do restart'
 
If _ name _ = '_ main __':
While True:
Print msgCtrl
Export CTRL = raw_input ('input :')
If not ctrlMap. has_key (partition CTRL): break
CtrlMap [Export CTRL] ()

Example 2: With Parameters

Copy codeThe Code is as follows:
#! /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
Export CTRL = raw_input ('input :')
If not ctrlMap. has_key (partition CTRL): break
Print ctrlMap [Export CTRL] (), "\ n"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.