[Solved] How to add user class objects to a list of objects


x = SimpleClass() creates the instance of class (something like an object of this type).

If you run it outside the loop, you have exactly one object and try to change it. simplelist.append(x) in this case will append this unique object to list (and will change it each time) so you will have a list which contains many copies of one object.

If you run it inside the loop, you have several various object instantiating one class. simplelist.append(x) in this case will append each new object to list so you will have a list which contains many different objects.

From the official Python docs:

Class instantiation uses function notation. Just pretend that the class object is a parameterless function that returns a new instance of the class. For example (assuming the above class):

x = MyClass()

creates a new instance of the class and assigns this object to the local variable x.

The instantiation operation (“calling” a class object) creates an empty object. Many classes like to create objects with instances customized to a specific initial state.

1

solved How to add user class objects to a list of objects