Home > Software design >  Python class data initialization
Python class data initialization

Time:11-30

I have a class like this

class Tree:
# class attributes:
a = []
b = None

def __init__(self, b, a_list):
    self.b = b
    if a_list is not None:
         initialize_a_list(a_list)

def initialize_a_list(self, a_list):
    self.a.append(a_list)

When I make this call, tree = Tree(b, None). My tree object's a was not initialized with an empty list but a random non-empty list. Before that I've created some other object of type Trees and I notice some of the elements in tree's a has the same elements as a of those objects created earlier.

I added a = [] in the __init__ function to the code to address the issue, but I was wondering why that was the case. Why was a initialized with such maybe-not-so-random but non-empty list.

CodePudding user response:

Instance variables aren't supposed to be declared like:

class Tree:
# class attributes:
a = []
b = None

Removed those lines, and it worked.

CodePudding user response:

Before that I've created some other object of type Trees and I notice some of the elements in tree's a has the same elements as a of those objects created earlier.

That is because you have declared the a variable as a class variable. This means that it is shared by all instances of the class, and the class itself.

Initializing the a variable in the __init__ method causes it to be an instance variable, which means it is owned individually by each instance of the class (a separate data structure is allocated to and handled by each instance).

Lastly, it's worth noting that a was indeed initialized as an empty list, it's just that other Tree instances wrote to that shared list, causing it to appear as though it held random data.

  • Related