How to convert a string to a function name in python?

前端 未结 9 2053
迷失自我
迷失自我 2020-11-27 12:55

For example, if I have a function called add like

def add(x,y):
    return x+y

and I want the ability to convert a string or a

9条回答
  •  难免孤独
    2020-11-27 13:25

    If you are implementing a shell-like application where the user enter some command (such as add), and the application responses (return the sum), you can use the cmd module, which handles all the command interactions and dispatching for you. Here is an example:

    #!/usr/bin/env python
    
    import cmd
    import shlex
    import sys
    
    class MyCmd(cmd.Cmd):
        def do_add(self, arguments):
            '''add - Adds two numbers the print the sum'''
            x, y = shlex.split(arguments)
            x, y = int(x), int(y)
            print x + y
    
        def do_quit(self, s):
            '''quit - quit the program'''
            sys.exit(0)
    
    if __name__ == '__main__':
        cmd = MyCmd()
        cmd.cmdloop('type help for a list of valid commands')
    

    Here is a sample running session:

    $ python cmd_tryout.py
    type help for a list of valid commands
    (Cmd) help add
    add - Adds two numbers the print the sum
    (Cmd) add 5 3
    8
    (Cmd) quit

    At the prompt (Cmd), you can issue the help command which you get for free. Other commands are add and quit which correspond to the do_add() and do_quit() functions.

    Note that help command displays the docstring for your function. The docstring is a string immediately follows the function declararation (see do_add() for example).

    The cmd module does not do any argument spliting, parsing, so you have to do it yourself. The do_add() function illustrates this.

    This sample program should be enough to get you started. For more information look up the cmd help page. It is trivia to customize the prompt and other aspect of your program.

提交回复
热议问题