2

The code below creates a list of objects that contains a list as attribute and a method to append items to this list but this appending is not working like I expected.

What I expected:
Each list MyList inside of each object MyObj to have only 3 elements.

How it is working:
The list MyList inside of MyObj[0] has 3 elements
The list MyList inside of MyObj[1] has 6 elements
The list MyList inside of MyObj[2] has 9 elements

It seems to me the object MyObj[i] appends the MyList of prevous object MyObj[i-1]. How the code should be like to make each list MyList of each MyObj[i] have only the 3 elements inserted by the method add_to_list?

Python code:

class MyClass:
    MyList = []

    def add_to_list(self):

        for item in range(3):
            self.MyList.append("Item " + str(item))


MyObj = []

for i in range(3):
    MyObj.append(MyClass())
    MyObj[i].add_to_list()

    print("Object " + str(i))
    print(MyObj[i].MyList)
Cleber Marques
  • 426
  • 5
  • 20
  • 1
    You can define MyList inside the init function in your class like this, `class MyClass: def __init__(self): self.MyList = []` Your main issue is you are using class variable MyList, which is shared among all objects of the same class, that's why it retains previous values. Defining it inside an init function and initializing it properly ensures it is unique for each object. Your question has already marked as a duplicate, so I can't post the answer in details. But I hope my comment helps you. – Saeed Jul 02 '19 at 02:57
  • 1
    Thank you @Saeed. That was the solution for me – Cleber Marques Jul 10 '19 at 04:33
  • You're welcome. Happy to help :) – Saeed Jul 10 '19 at 05:44

1 Answers1

2

You also need to add a line of MyObj[i].MyList.clear():

MyObj = []

for i in range(3):
    MyObj.append(MyClass())
    MyObj[i].add_to_list()

    print("Object " + str(i))
    print(MyObj[i].MyList)
    MyObj[i].MyList.clear()

Output:

Object 0
['Item 0', 'Item 1', 'Item 2']
Object 1
['Item 0', 'Item 1', 'Item 2']
Object 2
['Item 0', 'Item 1', 'Item 2']
U13-Forward
  • 69,221
  • 14
  • 89
  • 114