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 trying to do is a function that takes away the quotes of a list element and then executes the function that is in that list element.
def func():
print "python"
def func1():
print "is"
def func2():
print "awesome"
def do(fun):
fun()
#I think the problem is here
funs = ['func()','func1()','func2()']
print ''.join(funs[0])
do(''.join(funs[0]))
Edit:
What im trying to do is a function that takes away the quotes of a list element and then executes the function that is in that list element
答案 0 :(得分:5)
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()
答案 1 :(得分:3)
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))
答案 2 :(得分:2)
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.
答案 3 :(得分:0)
正如上面的人所说的最好的方法是定义一个函数字典,因为函数是python中的对象,这是可能的
def One():
pass
def Two():
pass
functions = {"ONE":One, "TWO":Two}
然后你可以这样称呼它:
functions[input]()
如果你想给用户真正的控制(我不建议这样做)你可以使用eval函数。
eval(input+"()")