python函数调用变量

pkd*_*dkk 11 python

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?
Run Code Online (Sandbox Code Playgroud)

Joh*_*ica 24

您可以将实际的函数对象本身用作键,而不是函数的名称.函数是Python中的第一类对象,因此直接使用它们比使用它们的名称更清晰,更优雅.

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

for key, val in test.items():
    key()
Run Code Online (Sandbox Code Playgroud)


chr*_*ock 7

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

def test():
        print 'test'

def test2():
        print 'test2'

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

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

  • 噢,不知道为什么你会在“函数对象作为键本身”方法上使用它。如果有的话,您可能会使用“hasattr”之类的东西进行内省,但永远不要使用“eval” (2认同)
  • ...例如,也许在“globals()”和/或“locals()”中查找名称?:) (2认同)

dhe*_*aur 7

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