类和列表的Python编程问题

时间:2015-03-17 07:57:01

标签: python list class

我正在使用Python进行编码,一个错误让我注意到了这一点。

说,我有这段代码:

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

我在两者之间有相同的代码,除了一个是列表而一个不是。为什么我会得到不同的结果?

1 个答案:

答案 0 :(得分:0)

在代码中,我们不是为list创建新变量,我们只是创建引用变量名。

演示:

>> l1 = ["hello"]
>>> l1= l1
>>> l2= l1
>>> id(l1), id(l2)
(3071912844L, 3071912844L)
>>> l1
['hello']
>>> l2
['hello']
>>> l2[0] = "goodbye"
>>> l2
['goodbye']
>>> l1
['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]]
>>> 

Link