Python 会在赋值时复制对象吗? [英] Does Python make a copy of objects on assignment?

查看:47
本文介绍了Python 会在赋值时复制对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望下面的代码只会初始化 dict_adict_bdict_c 字典.但它接缝有一个复制通过效果:

dict_a = dict_b = dict_c = {}dict_c['hello'] = '再见'打印 dict_a打印 dict_b打印 dict_c

如您所见,结果如下:

{'hello': '再见'}{'你好再见'}{'你好再见'}

为什么那个程序给出以前的结果,我希望它什么时候返回:

<代码>{}{}{'你好再见'}

解决方案

这是因为在 Python 中,变量(名称)只是对单个对象的引用.当您分配 dict_a = dict_b 时,您实际上是在将内存地址(或指针,如果您愿意)从 dict_b 复制到 dict_a.那本字典还有一个实例.

要获得所需的行为,请使用 dict.copy 方法,如果您的 dict 可能有嵌套的 dicts 或其他嵌套对象,请使用 copy.deepcopy.><预><代码>>>>a = {1:2}>>>b = a.copy()>>>乙{1:2}>>>b[3] = 4>>>一种{1:2}>>>乙{1: 2, 3: 4}>>>

I would expect that the following code would just initialise the dict_a, dict_b and dict_c dictionaries. But it seams to have a copy through effect:

dict_a = dict_b = dict_c = {}
dict_c['hello'] = 'goodbye'

print dict_a
print dict_b
print dict_c

As you can see the result is as follows:

{'hello': 'goodbye'}
{'hello': 'goodbye'}
{'hello': 'goodbye'}

Why does that program give the previous result, When I would expect it to return:

{}
{}
{'hello': 'goodbye'}

解决方案

This is because in Python, variables (names) are just references to individual objects. When you assign dict_a = dict_b, you are really copying a memory address (or pointer, if you will) from dict_b to dict_a. There is still one instance of that dictionary.

To get the desired behavior, use either the dict.copy method, or use copy.deepcopy if your dict may have nested dicts or other nested objects.

>>> a = {1:2}
>>> b = a.copy()
>>> b
{1: 2}
>>> b[3] = 4
>>> a
{1: 2}
>>> b
{1: 2, 3: 4}
>>> 

这篇关于Python 会在赋值时复制对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆