簡體   English   中英

在Python中創建對象列表

[英]Creating a list of objects in Python

我正在嘗試創建一個打開多個數據庫並比較其內容的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的元素,以便每個條目包含一個不同的對象實例而不是所有指向同一個實例?

你表現出一種根本的誤解。

你根本沒有創建過SimpleClass的實例,因為你沒有調用它。

for count in xrange(4):
    x = SimpleClass()
    x.attr = count
    simplelist.append(x)

或者,如果讓類使用參數,則可以使用列表推導。

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

要使用單獨的實例填充列表,可以在列表的聲明中使用for循環。 * multiply將每個副本鏈接到同一個實例。

instancelist = [ MyClass() for i in range(29)]

然后通過列表的索引訪問實例。

instancelist[5].attr1 = 'whamma'

如果你只是簡單地使用它來根據其屬性輸出數據,那么每次都不需要重新創建SimpleClass對象。 但是,您實際上並沒有創建該類的實例; 您只是創建對類對象本身的引用。 因此,您一遍又一遍地向列表(而不是實例屬性)添加對同一類屬性的引用。

代替:

x = SimpleClass

你需要:

x = SimpleClass()

每次創建一個新實例,其中每個新實例都具有正確的狀態,而不是不斷修改同一實例的狀態。

或者,在每個步驟存儲一個明確制作的對象副本(使用此頁面上的提示),而不是原始副本。

如果我正確理解了您的問題,您就會想辦法執行對象的深層復制。 那么使用copy.deepcopy呢?

import copy

x = SimpleClass()

for count in range(0,4):
  y = copy.deepcopy(x)
  (...)
  y.attr1= '*Bob* '* count

deepcopy是整個對象的遞歸副本。 有關更多參考,您可以查看python文檔: https//docs.python.org/2/library/copy.html

我認為這只是展示了你想要實現的目標:

# coding: utf-8

class Class():
    count = 0
    names = []

    def __init__(self,name):
        self.number = Class.count
        self.name = name
        Class.count += 1
        Class.names.append(name)

l=[]
l.append(Class("uno"))
l.append(Class("duo"))
print l
print l[0].number, l[0].name
print l[1].number, l[1].name
print Class.count, Class.names

運行上面的代碼,你得到: -

[<__main__.Class instance at 0x6311b2c>, 
<__main__.Class instance at 0x63117ec>]
0 uno
1 duo
2 ['uno', 'duo']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM