I’m trying to create a list of objects that hold a list themselves. I’m creating this from another list of elements.
class Test():
temp_list = list()
x = [['a','b','c'],['g','f','h']]
list_of_obj = list()
for i in x:
test = Test()
for b in i:
test.temp_list.append(b)
list_of_obj.append(test)
for obj in list_of_obj:
print(obj)
The idea in the above code is to split the list of lists (x) into 2 objects that hold all their elements.
However, when I print the temp_list in the objects, both lists have all the elements in x.
OUTPUT
['a', 'b', 'c', 'g', 'f', 'h']
['a', 'b', 'c', 'g', 'f', 'h']
Expected Output
['a', 'b', 'c']
['g', 'f', 'h']
>Solution :
This is because temp_list is a class attribute. Class attributes are not unique to instances of the class . They are universal to all instances.
What you want to do is create and instance attribute for temp_list Like this:
class Test():
def __init__(self):
self.temp_list = []
...
Per Random Davis suggestion in the comments:
If you want to be able to print the class directly you should also add this method to your class.
def __str__(self):
return str(self.temp_list)