【问题标题】:Understanding Python memory management with dict [duplicate]使用 dict 理解 Python 内存管理 [重复]
【发布时间】:2014-08-18 14:51:49
【问题描述】:

当我使用dict 编写一些 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

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

我想知道更多关于Python这种内存管理机制的细节,谁能给我一些好的参考资料解释一下?另外,当我们在Python中使用listsetstr时,有没有类似的行为?

【问题讨论】:

    标签: python memory dictionary


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2022-11-13
      • 2020-07-19
      • 2014-03-16
      • 1970-01-01
      • 1970-01-01
      • 2020-07-30
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多