3

I have a problem with objects.

The following code

class Data:
    def __init__(self,data=[]):
        self.data = data
    def add(self,data):
        self.data.extend(data)

class Parent:
    def testa(self):
        a = Data()
        a.add('a')
        print a.data
    def testb(self):
        b = Data()
        b.add('b')
        print b.data

if __name__ == "__main__":
    p = Parent()
    p.testa()
    p.testb()

Generates the following output:

[]
['a']
['a']
['a', 'b']

Why is there not a new object created? The second time in testb it seems that the old Data object still exists, although it was in a private variable.

How can I change the code so that a new object is created?

1
  • Don't forget to accept an answer that works for you by clicking on the green checkmark. Commented Mar 13, 2012 at 21:33

1 Answer 1

10

Using [] as a default argument to a function will only create a list once, and reuse this list on each call. See http://docs.python.org/tutorial/controlflow.html#default-argument-values for an explanation. Thus, both Data objects share the list referenced by their self.data member!

You should modify your code like this:

class Data:
    def __init__(self, data=None):
        if data is None:
            data=[]
        self.data = data
    def add(self, data):
        self.data.extend(data)

This should fix your problem.

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

1 Comment

@BartVanherck, if this solve your issue you should mark this answer as solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.