Python creating class instances in a loop [duplica

2019-08-29 10:29发布

This question already has an answer here:

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.

1条回答
狗以群分
2楼-- · 2019-08-29 11:07

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

查看更多
登录 后发表回答