{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_dict
、new_dict
和foo
函数中的bar_dict
都指向内存地址。实际上只有一个dict
对象存储在内存中,即使我在函数中传递了一个dict
。
我想了解更多关于Python这种内存管理机制的细节,有谁能给我一些好的参考资料来解释一下吗?另外,当我们在Python中使用list
、set
或{
Python名称只是对堆中存储的对象的引用。将对象传递给函数调用只是传递这些引用,将参数名称绑定到同一对象。在
您创建了一个dictionary对象,并将
old_dict
绑定到该对象。然后将该名称传递给foo()
函数,将本地名称bar_dict
绑定到同一对象。然后在函数中操纵该对象并返回它。您将对返回对象的引用存储在new_dict
中,结果是两个全局名称引用同一对象。在相关问题 更多 >
编程相关推荐