问题描述
我正在尝试创建一个Python脚本,该脚本可以打开多个数据库并比较它们的内容.在创建该脚本的过程中,我遇到了一个创建列表的问题,该列表的内容是我创建的对象.
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?
这是我的简化代码
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
那么,如何(简单地添加,扩展,复制或其他方式)simpleList的元素,以便每个条目都包含对象的不同实例,而不是全部都指向同一对象?
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.
您根本没有创建SimpleClass的实例,因为您没有调用它.
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)]
这篇关于在Python中创建对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!