A function that calls X function

后端 未结 4 397
借酒劲吻你
借酒劲吻你 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))
    
    0 讨论(0)
  • 2021-01-17 06:33

    You don't need the extra functions, and you don't need to turn them into a string either:

    def func():
        print "python"
    
    def func1():
         print "is"
    
    def func2():
         print "awesome"
    
    funcs = [func, func1, func2]
    
    for function in funcs:
        function()
    
    0 讨论(0)
  • 2021-01-17 06:40

    As the people above have said the best way is to define a dictionary of functions, as functions are objects in python this is possible

    def One():
       pass
    def Two():
       pass
    functions = {"ONE":One, "TWO":Two}
    

    You can then call it like this:

    functions[input]()
    

    If you want to give true control to the user (And I DO NOT recommend doing this) you could use the eval function.

    eval(input+"()")
    
    0 讨论(0)
  • 2021-01-17 06:46

    If you really want to execute arbitrarily named functions from a list of names in the current global/module scope then this will do:

    NB: This does NOT use the potentially unsafe and dangerous eval():

    Example:

    def func():
        return "python"
    
    
    def func1():
        return "is"
    
    
    def func2():
        return "awesome"
    
    
    def do(func_name, *args, **kwargs):
        f = globals().get(func_name, lambda : None)
        if callable(f):
            return f(*args, **kwargs)
    
    
    funs = ["func", "func1", "func2"]
    
    print "".join(funs[0])
    print "".join(map(do, funs))
    

    Output:

    $ python foo.py
    func
    pythonisawesome
    

    You can also individually call "named" functions:

    >>> do(funs[0])
    python
    

    Note the implementation of do(). This could also be applied more generically on objects and other modules too swapping out globals() lookups.

    0 讨论(0)
提交回复
热议问题