A function that calls X function

后端 未结 4 401
借酒劲吻你
借酒劲吻你 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: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.

提交回复
热议问题