【发布时间】:2017-08-06 14:34:12
【问题描述】:
我有以下问题,在详细解释之前,我想先展示以下两个最小类来说明:
class Example1:
def __init__(self):
pass
def function11(self,x):
x=2*x+1
return x
def function12(self,x):
y=0
z=x
while y<z:
x=self.function11(x)
y=y+1
return x
class Example2:# the only difference to the previous class: it handles
#lists instead of numbers
def __init__(self):
pass
def function21(self,x):
x[0]=2*x[0]+1
return x
def function22(self,x):
y=0
z=x[0]
while y<z:
x=self.function21(x)
y=y+1
return x
if __name__=="__main__":
A1=Example1()
x1=A1.function11(3)
y1=A1.function12(x1)
print'Result of Example1:'
print x1
print y1
print
A2=Example2()
x2=A2.function21([3])
y2=A2.function22(x2)
print'Result of Example2:'
print x2
print y2
这是输出:
Result of Example1:
7
1023
Result of Example2:
[1023]
[1023]
>>>
我在这里不明白的是:为什么变量 x2 会被 y2 的值覆盖?这显然取决于列表是 Python 中的可变对象这一事实,对吗?我对此的搜索使我找到了Effbot 的一篇文章。不过,我真的不明白这里发生了什么。
【问题讨论】:
-
因为,在
Example2.function21中,您正在传递一个列表对象并通过其索引对其进行变异(在x[0]=2*x[0]+1中)。在Example1.function11中,您并没有改变原始变量(只是通过x=2*x+1将名称重新分配给不同的对象) -
阅读 this answer 可能会有所帮助