使用di理解Python内存管理

2024-06-02 06:13:13 发布

您现在位置:Python中文网/ 问答频道 /正文

{I>在编写Python代码时发现以下行为:

In [1]: def foo(bar_dict):
   ...:     print id(bar_dict)
   ...:     bar_dict['new'] = 1
   ...:     return bar_dict
   ...: 

In [2]: old_dict = {'old':0}

In [3]: id(old_dict)
Out[3]: 4338137920

In [4]: new_dict = foo(old_dict)
4338137920

In [5]: new_dict
Out[5]: {'new': 1, 'old': 0}

In [6]: id(new_dict)
Out[6]: 4338137920

In [7]: old_dict
Out[7]: {'new': 1, 'old': 0}

In [8]: id(old_dict)
Out[8]: 4338137920

old_dictnew_dictfoo函数中的bar_dict都指向内存地址。实际上只有一个dict对象存储在内存中,即使我在函数中传递了一个dict

我想了解更多关于Python这种内存管理机制的细节,有谁能给我一些好的参考资料来解释一下吗?另外,当我们在Python中使用listset或{}时,是否存在类似的行为?


Tags: 函数内存代码inidnewreturnfoo
1条回答
网友
1楼 · 发布于 2024-06-02 06:13:13

Python名称只是对堆中存储的对象的引用。将对象传递给函数调用只是传递这些引用,将参数名称绑定到同一对象。在

您创建了一个dictionary对象,并将old_dict绑定到该对象。然后将该名称传递给foo()函数,将本地名称bar_dict绑定到同一对象。然后在函数中操纵该对象并返回它。您将对返回对象的引用存储在new_dict中,结果是两个全局名称引用同一对象。在

相关问题 更多 >