我正在尝试创建一个Python脚本,用于打开几个数据库并比较它们的内容。在创建该脚本的过程中,我在创建一个以我创建的对象为内容的列表时遇到了一个问题。
为了这篇文章,我已经将程序简化到最基本的部分。首先,我创建一个新类,创建它的一个新实例,为它分配一个属性,然后将它写到一个列表中。然后,我为实例分配一个新值,并再次将其写入列表……一次又一次..。
问题是,它总是相同的对象,所以我实际上只是改变了基对象。当我阅读列表时,我会一遍又一遍地重复相同的对象。
那么,如何在循环中将对象写入列表呢?
以下是我的简化代码
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的元素,使每个条目都包含对象的不同实例,而不是全部指向同一个实例?
发布于 2008-12-07 22:22:40
你证明了一个根本的误解。
您根本没有创建SimpleClass的一个实例,因为您没有调用它。
for count in xrange(4):
x = SimpleClass()
x.attr = count
simplelist.append(x)
或者,如果让类接受参数,则可以使用列表理解。
simplelist = [SimpleClass(count) for count in xrange(4)]
发布于 2008-12-09 11:50:39
要用类的单独实例填充列表,可以在列表的声明中使用for循环。乘法会将每个副本链接到同一个实例。
instancelist = [ MyClass() for i in range(29)]
然后通过列表的索引访问实例。
instancelist[5].attr1 = 'whamma'
发布于 2008-12-07 23:06:59
如果您只是简单地使用SimpleClass对象来根据其属性输出数据,则不必每次都重新创建该对象。但是,您实际上并没有创建类的实例;您只是创建了对类对象本身的引用。因此,您一遍又一遍地向列表(而不是实例属性)添加对同一class属性的引用。
而不是:
x = SimpleClass
您需要:
x = SimpleClass()
https://stackoverflow.com/questions/348196
复制相似问题