python中的引用问题

时间:2011-04-07 11:43:49

标签: python

为什么赋值运算符不是复制rvalue而是复制它(在列表中),并且你必须使用切片才能创建一个真正的副本来创建一个独立的对象,以便在一个不影响对方。这是否与我迄今为止错过的语言相关的某些特定用法有关?

编辑:我在P ++中提到的是

int a = 1;
int b = a;
b = 2;    // does not affect a 

所以我也认为这是相同的推理,因为Python是用C开发的,它最有可能用指针来处理它。使用一些简单的代码:

int a = 1; 
/*int b = a;*/
int &b = a; /* what python does as I understood, if so why it does that this way?*/ 

更清楚了吗?

我问的是一个比较问题,我应该更清楚,我同意; - )

2 个答案:

答案 0 :(得分:2)

在python中,一切都可以被视为参考。如果你想让一个作业成为一个副本,你总是需要在你的表达中加以表达

a = range(10) # create a list and assign it to "a"
b = a  # assign the object referenced by "a" to b
a is b # True --> a and b are two references to the same object. Works with any object 
       # after b = a
from copy import deepcopy
c = deepcopy(a) # or c = a[:] for lists
c is a # False

答案 1 :(得分:2)

我最近发布了answer,正好讨论了这个问题。