Implementing a similar structure function call method in Python

Source: Internet
Author: User
Python's dict is easy to use, and you can customize the key value and access it through the following example:
Copy CodeThe code is as follows:


>>> d = {' Key1 ': ' value1 ',
... ' Key2 ': ' value2 ',
... ' Key3 ': ' Value3 '}
>>> print d[' Key2 ']
value2
>>>


Lambda expressions are also useful, as shown in the following example:
Copy CodeThe code is as follows:


>>> f = Lambda x:x**2
>>> print F (2)
4
>>>


The combination of the two can implement similar function calls, which are convenient to use, as shown in the following example:

example one: without parameters
Copy the Code code 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 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: with parameters

Copy the Code code 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
Cmdctrl = raw_input (' Input: ')
If not Ctrlmap.has_key (Cmdctrl): Break
Print Ctrlmap[cmdctrl] (10,2), "\ n"
  • Related Article

    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.