2

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)

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.

2
  • 1
    self.checklist = parent.checklist should raise AttributeError if parent=None, I think it should be in if statement. And also, use parent is not None instead of != and don't use parantheses with if statement(with one condition). Commented Aug 15, 2011 at 14:39
  • Sorry. That was a copying error. corrected. Commented Aug 15, 2011 at 14:41

2 Answers 2

6

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[:]

Sign up to request clarification or add additional context in comments.

1 Comment

Yes. That did the job. Thanks a lot. Didn't know about this static-like behaviour.
1

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.

2 Comments

so what do we do to even copy that?
I am not sure what you mean. Use copy.deepcopy when you want to make an unconnected copy of an object and are not 100% convinced it has no child objects. In general use deepcopy everytime you want an unrelated copy. But in general copying mutable objects is often a sign you can fo it simpler another way

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.