A function that calls X function

后端 未结 4 399
借酒劲吻你
借酒劲吻你 2021-01-17 05:41

I want to basically turn a list element into a function with the do function. This way any pre-written funcction i can call by just use a do(list[x]).

What im tryin

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-17 06:27

    Well, it basically works like this. Note that the list contains the functions themselves, not a string.

    def func():
       print "python"
    
    def func1():
        print "is"
    
    def func2():
        print "awesome"
    
    def do(fun):
        fun()
    
    funcs = [func, func1, func2]
    
    for function in funcs:
        do(function)
    

    Output:

    python
    is
    awesome
    

    EDIT: If you do want the list to contain the functions' names as strings, use eval():

    funcs = ['func', 'func1', 'func2']
    
    for function in funcs:
        do(eval(function))
    

提交回复
热议问题