簡體   English   中英

Python:新 Object 丟失數組屬性

[英]Python: New Object loses array attributes

我目前正在編寫一個 python 程序,該程序應該創建一個已創建的 class 對象數組。

我面臨的問題是,class 有一個數組作為屬性。 在我執行 myArray.clear() 之后,class object 會丟失數組值。 其他值不會丟失。 我知道這是由於數組的引用,但我不知道如何解決這個問題。

代碼示例:

Class

class Testclass(object):
   def __init__(self, array, normalValue):
    self._array= array
    self._normalValue= normalValue
    

主要的

if __name__=="main":
   exampleIteratorArray = ["Ex1", "Ex2", "Ex3"]
   objectArray = []
   for i, value in enumerate(exampleIteratorArray):
         exampleArray = [i, i+1, i+2]
         objectArray.append(Testclass(exampleArray, value))
         exampleArray.clear()              #I have to do this because I want to check the state depending on the value of this variable (in my main code)
                                            #After the exampleArray.clear(), the objectArray loses the exampleArray values but not the i value

因此,我想知道如何在每次迭代后不丟失值的情況下將對象添加到數組中。 提前致謝: :)

編輯

正如 Azro 指出的那樣,我每次迭代都從 exampleArray 創建一個新變量,因此我不需要清除數組。

在 Python 中,列表分配指的是列表的相同(原始)實例。 當您清除本地數組時,您同時清除了本地數組和您認為復制到 object 中的數組(但實際上沒有),因為它們實際上是同一個數組。

簡單的例子:

a = [1, 2, 3]
b = a
a.append(4)
print(b)
# prints [1, 2, 3, 4]

要將數組分配/復制為單獨的 object,您需要使用復制或深復制操作。 當前代碼中的一種簡單方法是切片復制:

objectArray.append(Testclass(exampleArray[:], value))

注意添加的[:]

暫無
暫無

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

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