简体   繁体   English

python函数调用变量

[英]python function call with variable

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?

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()

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

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()函数的名称发生冲突。

def test():
    print 'test'

def test2():
    print 'test2'

assign_list=[test,test2]

for i in assign_list:
    i()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM