python创建对象_在Python中创建对象列表

1586010002-jmsa.png

I'm trying to create a Python script that opens several databases and compares their contents. In the process of creating that script, I've run into a problem in creating a list whose contents are objects that I've created.

I've simplified the program to its bare bones for this posting. First I create a new class, create a new instance of it, assign it an attribute and then write it to a list. Then I assign a new value to the instance and again write it to a list... and again and again...

Problem is, it's always the same object so I'm really just changing the base object. When I read the list, I get a repeat of the same object over and over.

So how do you write objects to a list within a loop?

Here's my simplified code

class SimpleClass(object):

pass

x = SimpleClass

# Then create an empty list

simpleList = []

#Then loop through from 0 to 3 adding an attribute to the instance 'x' of SimpleClass

for count in range(0,4):

# each iteration creates a slightly different attribute value, and then prints it to

# prove that step is working

# but the problem is, I'm always updating a reference to 'x' and what I want to add to

# simplelist is a new instance of x that contains the updated attribute

x.attr1= '*Bob* '* count

print "Loop Count: %s Attribute Value %s" % (count, x.attr1)

simpleList.append(x)

print '-'*20

# And here I print out each instance of the object stored in the list 'simpleList'

# and the problem surfaces. Every element of 'simpleList' contains the same attribute value

y = SimpleClass

print "Reading the attributes from the objects in the list"

for count in range(0,4):

y = simpleList[count]

print y.attr1

So how do I (append, extend, copy or whatever) the elements of simpleList so that each entry contains a different instance of the object instead of all pointing to the same one?

解决方案

You demonstrate a fundamental misunderstanding.

You never created an instance of SimpleClass at all, because you didn't call it.

for count in xrange(4):

x = SimpleClass()

x.attr = count

simplelist.append(x)

Or, if you let the class take parameters, instead, you can use a list comprehension.

simplelist = [SimpleClass(count) for count in xrange(4)]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值