使用变量调用Python函数
在编程中,有时候我们会遇到一些问题,想要找到解决方案。比如,有人可能在使用某个工具或库时,遇到了错误或者不明白怎么用。这时候,大家会去一个叫StackOverflow的网站上提问,那里有很多程序员会分享他们的经验和解决办法。
在这个网站上,用户可以描述他们遇到的问题,提供一些代码示例,甚至是错误信息。其他人看到后,可以给出建议或者解决方案,帮助提问者解决问题。
总之,StackOverflow是一个很好的地方,可以让程序员们互相帮助,分享知识,解决编程中的各种难题。
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?
4 个回答
0
def test():
print 'test'
def test2():
print 'test2'
assign_list=[test,test2]
for i in assign_list:
i()
当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。
7
约翰有一个不错的解决方案。这里还有另一种方法,使用 eval()
:
def test():
print 'test'
def test2():
print 'test2'
mydict = {'test':'blabla','test2':'blabla2'}
for key, val in mydict.items():
eval(key+'()')
注意,我把字典的名字改了,以避免和 test()
函数的名字冲突。
41
你可以直接使用函数本身作为键,而不是使用函数的名字。在Python中,函数被视为一等公民,所以直接使用函数对象会更简洁、更优雅。
test = {test:'blabla', test2:'blabla2'}
for key, val in test.items():
key()