【问题标题】:python function call with variable带变量的python函数调用
【发布时间】:2010-12-13 16:50:36
【问题描述】:
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?

【问题讨论】:

标签: python


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 哎呀,不知道为什么你会在“函数对象作为键本身”方法上使用它。如果有的话,您可能会使用 hasattr 之类的东西进行自省,但永远不会使用 eval
    • @Daniel 我没说它漂亮! :D
    • 这行得通,但是eval() 有很多开销来使用它只是调用一个函数。还有其他更好、更“Pythonic”的方式......
    • ... 例如,在globals() 和/或locals() 中查找名称? :)
    【解决方案3】:
    def test():
        print 'test'
    
    def test2():
        print 'test2'
    
    assign_list=[test,test2]
    
    for i in assign_list:
        i()
    

    【讨论】:

    • 在assign_list测试中,test2给直接方式,即[test,test2]
    • for i in assign_list: this next line i()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 2019-10-05
    相关资源
    最近更新 更多