开发者

Unexpected result in Python class initialization

I wrote following code:

class node:
    def __init__(self, title, series, parent):
        self.series = series
        self.title = title
        self.checklist = []
        if(parent != None):
            self.checklist = parent.checklist
        self.checklist.append(self)
开发者_StackOverflow社区

When I create objects like this:

a = node("", s, None)
b = node("", s, a)
print a.checklist

Unexpectedly, it shows both a and b objects as an output of print statement. I am new to python. So, possibly there's some stupid mistake.

Thank you.


You do self.checklist = parent.checklist which means that both instances share the same list. They both add themselves to it, so when you print it you see both instances.

Maybe you wanted to make a copy of the parent list? self.checklist = parent.checklist[:]


Be careful of the slice notation [:] This will make a copy of the list, but if the list contains other lists, those lists themselves will be copied over by reference, not as new objects.

for example::

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> x = [a,b]
>>> y = x[:]
>>> x
[[1, 2, 3], [4, 5, 6]]
>>> y
[[1, 2, 3], [4, 5, 6]]
>>> a.append(66)
>>> x
[[1, 2, 3, 66], [4, 5, 6]]
>>> y
[[1, 2, 3, 66], [4, 5, 6]]

     ^^^^^^^^^  unexpectedly y has an updated a inside it, even though we copied it off.


>>> import copy
>>> y = copy.deepcopy(x)
>>> a.append(77)
>>> x
[[1, 2, 3, 44, 55, 66, 77], [4, 5, 6]]
>>> y
[[1, 2, 3, 44, 55, 66], [4, 5, 6]]

                     ^^^^^ y is a seperate object and so are all its children

You might be interested in using id(y) to see the memory address of the object y.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜