python循环构建多个类_Python在循环中创建类实例

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.

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值