What am I doing wrong? Saving Python object data from previous instance?

Can someone tell me what I am doing wrong or where my understanding is wrong?

It seems to me that the code below, which creates instances of two objects, should have separate data for each instance.

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 data from the first:

 >>> number of items in a: 1 a-data number of items in b: 1 a-data 
+4
source share
3 answers

You cannot use a mutable object as the default value. All objects will have the same mutable object.

Do it.

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

When you create a class definition, it creates a list object [] . Each time you instantiate a class, it uses the same list object as the default value.

+7
source

The problem is in this line:

 def __init__(self, data = []): 

When you write data = [] to set an empty list as the default value for this argument, Python creates the list only once and uses the same list for every method call without an explicit data argument. In your case, this happens when you create both a and b , since you do not specify an explicit list to any of the constructors, so both a and b use the same object as their data list. Any changes you make to one will be reflected in the other.

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

 def __init__(self, data=None): if data is None: data = [] 
+3
source

When providing default values ​​for a function or method, you usually want to provide immutable objects. If you provide an empty list or an empty dictionary, you will receive all calls to this function or method that share the object.

Good workaround:

 def __init__(self, data = None): if data == None: self.data = [] else: self.data = data 
+2
source

Source: https://habr.com/ru/post/1314492/


All Articles