Skip to main content
 首页 » 编程设计

python之从字典中调用函数

2025年05月04日15虾米姐

我想从字典中调用一个函数。是否可以?如果可以,我该怎么做?

def function(): 
    pass 
 
my_dic = { 
    'hello': function() 
} 

请您参考如下方法:

据我了解,您的实际意思是如何将函数引用保存在字典中,以便在通过键从字典中获取它后能够稍后调用它。这是可能的,因为函数是 first class objects在 Python 中:

>>> def function(): 
...     print("Hello World") 
...  
>>> d = { 
...     'hello': function  # NOTE: we are not calling the function here - just keeping the reference 
... } 
>>> d['hello']() 
Hello World 

带有一些用例示例的相关线程: