Pyhton 新手。
今天看教程的时候实验了如下代码:
old = 'abc'
old.replace('a','A')
print old
这里old 并没有被替换,这个我可以理解,因为replace方法返回了一个新的对象,old仍指向原对象。
所以打印的仍然是abc
替换成:
old = 'abc'
new = old.replace('a','A')
print new
即可。
结果就是Abc了。
但是,又想到了这个问题,代码如下:
stu1 = 'Tom'
stu2 = 'John'
classMates = [stu1,stu2]
print classMates
stu2 = 'Marry'
print classMates
结果却是:
['Tom','John']
['Tom','John']
而不是预期的:
['Tom','John']
['Tom','Marry']
如果再对list赋值一次:
classMates = [stu1,stu2]
就可以得到想要的效果。
所以想问的是list创建的时候指向的是stu1和stu2的位置么,为什么stu2中的内容变了list中的不会变呢?
还是像最开始的那个例子一样,产生了一个新的list?现在的classMates没有指向更改后的list而是还是指向原来的list?
谢谢!
You need to know what the assignment operation in Python means:
The simplest assignment, such as
a = b
, is to associate the object referred to byb
with the namea
, so you can use The namea
is used to refer to this object.a = b
,是将b
所指称的对象与名字a
关联起来,这样你就可以用名字a
来指称这个对象了。所以,你的代码的意思是:
So, your code means:stu2
rrreee
stu2
has no content, it's just the name. A name can refer to an object.These two sentences create two string objects: 'Tom' and 'John' and assign the references of these two objects to stu1 and stu2.
The two string objects become elements of the list, and the reference counts are +1 respectively, which is 2
'John' reference count -1 'Marry' reference count +1
Remember the difference between lists and variables. list is quoted. Both list and list2 point to the same address
The variables are not referenced.