Skip to main content
 首页 » 编程设计

python之如何在不多次调用函数的情况下访问函数内、函数外生成的字典。 PYTHON

2025年05月04日14jpfss

我有一个返回字典的函数。

我希望能够在代码中多次访问和使用该词典,而不需要每次都调用生成该词典的函数。换句话说,调用该函数一次,但多次使用它返回的字典。

因此,通过这种方式,字典只构造一次(可能存储在某个地方?),但在脚本中多次调用和使用。

def function_to_produce_dict(): 
    dict = {} 
    # something 
    # something that builds the dictionary  
    return dict  
 
 
create_dict = function_to_product_dict() 
 
# other code that will need to work with the create_dict dictionary.  
# without the need to keep constructing it any time that we need it.  

我读过其他帖子,例如: Access a function variable outside the function without using `global`

但我不确定通过使用 function_to_produce_dict() 将字典声明为全局字典是否可以使字典可访问,而不必每次都通过一次又一次地调用该函数来构建它。

这可能吗?

请您参考如下方法:

可能我没看懂,你已经在create_dict中保存了;继续使用 create_dict 中的字典即可。一旦将它存储在 create_dict 中,它就不会每次都被构建。

也许您应该重命名它,因为 create_dict 听起来像是一个创建字典的函数。也许这与您对此的困惑有关?