Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What am I doing wrong? Python object instantiation keeping data from previous instantiation?

Can someone point out to me what I'm doing wrong or where my understanding is wrong?

To me, it seems like the code below which instantiates two objects should have separate data for each instantiation.

class Node:
    def __init__(self, data = []):
        self.data = data

def main():
    a = Node()
    a.data.append('a-data') #only append data to the a instance

    b = Node() #shouldn't this be empty?

    #a data is as expected
    print('number of items in a:', len(a.data))
    for item in a.data:
        print(item)

    #b data includes the data from a
    print('number of items in b:', len(b.data))
    for item in b.data:
        print(item)

if __name__ == '__main__':
    main()

However, the second object is created with the data from the first:

>>> 
number of items in a: 1
a-data
number of items in b: 1
a-data
like image 709
KobeJohn Avatar asked Jul 01 '10 21:07

KobeJohn


2 Answers

You can't use an mutable object as a default value. All objects will share the same mutable object.

Do this.

class Node:
    def __init__(self, data = None):
        self.data = data if data is not None else []

When you create the class definition, it creates the [] list object. Every time you create an instance of the class it uses the same list object as a default value.

like image 135
S.Lott Avatar answered Sep 21 '22 03:09

S.Lott


The problem is in this line:

def __init__(self, data = []):

When you write data = [] to set an empty list as the default value for that argument, Python only creates a list once and uses the same list for every time the method is called without an explicit data argument. In your case, that happens in the creation of both a and b, since you don't give an explicit list to either constructor, so both a and b are using the same object as their data list. Any changes you make to one will be reflected in the other.

To fix this, I'd suggest replacing the first line of the constructor with

def __init__(self, data=None):
    if data is None:
        data = []
like image 20
David Z Avatar answered Sep 24 '22 03:09

David Z