【发布时间】: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_dict、new_dict 和bar_dict 都指向内存地址。实际上只有一个dict 对象存储在内存中,即使我在函数内部传递了一个dict。
我想知道更多关于Python这种内存管理机制的细节,谁能给我一些好的参考资料解释一下?另外,当我们在Python中使用list、set或str时,有没有类似的行为?
【问题讨论】:
标签: python memory dictionary