变量赋值和修改(在python中) [英] Variable assignment and modification (in python)

查看:79
本文介绍了变量赋值和修改(在python中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行此脚本(Python v2.6)时:

When I ran this script (Python v2.6):

a = [1,2]
b = a
a.append(3)
print a
>>>> [1,2,3]
print b
>>>> [1,2,3]

我希望print b输出[1,2].当我所做的只是改变a时,为什么b被改变了? b是否永久绑定到a?如果是这样,我可以使它们独立吗?怎么样?

I expected print b to output [1,2]. Why did b get changed when all I did was change a? Is b permanently tied to a? If so, can I make them independent? How?

推荐答案

Python中的内存管理涉及一个包含所有Python对象和数据结构的私有堆内存位置.

Memory management in Python involves a private heap memory location containing all Python objects and data structures.

Python的运行时仅处理对对象的引用(所有对象都驻留在堆中):Python堆栈上的内容始终是对其他位置的值的引用.

Python's runtime only deals in references to objects (which all live in the heap): what goes on Python's stack are always references to values that live elsewhere.

>>> a = [1, 2]

>>> b = a

>>> a.append(3)

在这里我们可以清楚地看到变量ba绑定到同一对象.

Here we can clearly see that the variable b is bound to the same object as a.

您可以使用is运算符来测试两个对象在物理上是否相同,这意味着它们在内存中是否具有相同的地址.也可以使用 id() 函数进行测试.

You can use the is operator to tests if two objects are physically the same, that means if they have the same address in memory. This can also be tested also using the id() function.

>>> a is b
>>> True
>>> id(a) == id(b)
>>> True

因此,在这种情况下,您必须明确要求副本. 完成此操作后,两个不同的列表对象之间将不再有连接.

So, in this case, you must explicitly ask for a copy. Once you've done that, there will be no more connection between the two distinct list objects.

>>> b = list(a)
>>> a is b
>>> False

这篇关于变量赋值和修改(在python中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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