Skip to content Skip to sidebar Skip to footer

Python Creating Class Instances In A Loop

I'm new to python, so I'm pretty confused now. I just want to create a couple of instances of class MyClass in a loop. My code: for i in range(1, 10): my_class = MyClass() prin

Solution 1:

_items is a class attribute, initialized during the class definition, so by appending values to it, you're modifying the class attribute and not instance attribute.

To fight the problem you can create _items for each instance of the class by putting this code into __init__ method:

classMyClass:def__init__(self):
        self._items = []

Then _items list object will be different across all class instances

>>>first = MyClass()>>>first._items.append(1)>>>second = MyClass()>>>second._items.append(1)>>>first._items is second._items
False

and therefore appending will work as expected.

Btw, in your case __items is not quite good name choice for a class variable.

Post a Comment for "Python Creating Class Instances In A Loop"