0

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()
  print "i = %d, items = %d" % (i, my_class.getItemsCount());
  my_class.addItem(i)

Class MyClass

class MyClass:

  __items = []

  def addItem(self, item):
    self.__items.append(item)

  def getItemsCount(self):
    return self.__items.__len__();

And the output is:

i = 0, items = 0
i = 1, items = 1
i = 2, items = 2
and so on...

But I expect new empty instance of MyClass in variable my_class on each iteration. So expected output is:

i = 0, items = 0
i = 1, items = 0
i = 2, items = 0

Could you help me with understanding? Thanks.

Alex
  • 59
  • 2
  • 7
  • 1
    `__items` is a class member, not an instance member. It is shared between all instances of `MyClass`. – juanchopanza Apr 26 '14 at 20:19
  • 2
    avoid using double underscore, it's only useful in rare cases of inheritance. Use the `len`-function instead of `__len__`-Method, e.g. `len(self._item)` – Daniel Apr 26 '14 at 20:27

1 Answers1

8

_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:

class MyClass:
    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.

vaultah
  • 44,105
  • 12
  • 114
  • 143