类和列表的Python编程问题
我用Python编写代码,一个bug让我注意到了这一点 比如,我有这个代码:类和列表的Python编程问题,python,list,class,Python,List,Class,我用Python编写代码,一个bug让我注意到了这一点 比如,我有这个代码: class test1(object): def __init__(self): self.hello = ["hello"] self.text_back = test2().stuff(self.hello) print "With list: ",self.hello[0], self.text_back[0] class test2(object):
class test1(object):
def __init__(self):
self.hello = ["hello"]
self.text_back = test2().stuff(self.hello)
print "With list: ",self.hello[0], self.text_back[0]
class test2(object):
def stuff(self,text1):
self.asdf = text1
self.asdf[0] = "goodbye"
return self.asdf
a = test1()
#---------------
class test3(object):
def __init__(self):
self.hello = "hello"
self.text_back = test4().stuff(self.hello)
print "Without list:",self.hello, self.text_back
class test4(object):
def stuff(self,text1):
self.asdf = text1
self.asdf = "goodbye"
return self.asdf
b = test3()
输出为:
With list: goodbye goodbye
Without list: hello goodbye
我有两个相同的代码,除了一个是列表,一个不是。为什么会得到不同的结果?在代码中,我们并没有为列表创建新变量,我们只是创建引用变量名 演示: 通常复制列表:
>>> l1 = [1,2,3]
>>> l2 = l1[:]
>>> id(l1), id(l2)
(3071912556L, 3071912972L)
>>> l1.append(4)
>>> l1
[1, 2, 3, 4]
>>> l2
[1, 2, 3]
>>>
嵌套数据结构:
>>> l1 = [1,2, [1,2], [3,4]]
>>> l2 = l1[:]
>>> l1.append(4)
>>> l1
[1, 2, [1, 2], [3, 4], 4]
>>> l2
[1, 2, [1, 2], [3, 4]]
>>> l1[2].append(3)
>>> l1
[1, 2, [1, 2, 3], [3, 4], 4]
>>> l2
[1, 2, [1, 2, 3], [3, 4]]
>>>
Python中的深度副本
>>> import copy
>>> l1 = [1,2, [1,2], [3,4]]
>>> l2 = copy.deepcopy(l1)
>>> l1.append(4)
>>> l1[2].append(3)
>>> l1
[1, 2, [1, 2, 3], [3, 4], 4]
>>> l2
[1, 2, [1, 2], [3, 4]]
>>>
>>> import copy
>>> l1 = [1,2, [1,2], [3,4]]
>>> l2 = copy.deepcopy(l1)
>>> l1.append(4)
>>> l1[2].append(3)
>>> l1
[1, 2, [1, 2, 3], [3, 4], 4]
>>> l2
[1, 2, [1, 2], [3, 4]]
>>>