Bart Vanherck
Bart Vanherck

Reputation: 76

creating new python objects seems to be the same object

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?

Upvotes: 3

Views: 348

Answers (1)

hochl
hochl

Reputation: 12960

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.

Upvotes: 10

Related Questions