带变量的python函数调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4431216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:41:58  来源:igfitidea点击:

python function call with variable

python

提问by pkdkk

def test():
    print 'test'

def test2():
    print 'test2'

test = {'test':'blabla','test2':'blabla2'}
for key, val in test.items():
    key() # Here i want to call the function with the key name, how can i do so?

采纳答案by John Kugelman

You could use the actual function objects themselves as keys, rather than the names of the functions. Functions are first class objects in Python, so it's cleaner and more elegant to use them directly rather than their names.

您可以使用实际的函数对象本身作为键,而不是函数的名称。函数是 Python 中的第一类对象,因此直接使用它们而不是它们的名称会更简洁、更优雅。

test = {test:'blabla', test2:'blabla2'}

for key, val in test.items():
    key()

回答by chrisaycock

John has a good solution. Here's another way, using eval():

约翰有一个很好的解决方案。这是另一种方式,使用eval()

def test():
        print 'test'

def test2():
        print 'test2'

mydict = {'test':'blabla','test2':'blabla2'}
for key, val in mydict.items():
        eval(key+'()')

Note that I changed the name of the dictionary to prevent a clash with the name of the test()function.

请注意,我更改了字典的名称以防止与test()函数名称发生冲突。

回答by dheerosaur

If what you want to know is "How to call a function when you have it's name in a string", here are some good answers - Calling a function of a module from a string with the function's name in Python

如果您想知道的是“如何在字符串中有函数名称时调用函数”,这里有一些很好的答案 -在 Python 中从带有函数名称的字符串中调用模块的函数

回答by Surya

def test():
    print 'test'

def test2():
    print 'test2'

assign_list=[test,test2]

for i in assign_list:
    i()