简体   繁体   English

Python:新 Object 丢失数组属性

[英]Python: New Object loses array attributes

I'm currently writing a python programm that should create an array of class objects, which a have created.我目前正在编写一个 python 程序,该程序应该创建一个已创建的 class 对象数组。

The problem I'm facing is, that the class has an array as attribute.我面临的问题是,class 有一个数组作为属性。 After I do myArray.clear() the class object loses the array values.在我执行 myArray.clear() 之后,class object 会丢失数组值。 The other values doesn't get lost.其他值不会丢失。 I know this is due to the reference of the array, but I don't know how to fix this.我知道这是由于数组的引用,但我不知道如何解决这个问题。

Code example:代码示例:

Class Class

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

Main主要的

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

Therefore, I wanted to know how I can add objects to the array without losing the values after each iteration.因此,我想知道如何在每次迭代后不丢失值的情况下将对象添加到数组中。 Thanks in advance: :)提前致谢: :)

Edit编辑

As Azro pointed out, I create a new varaible from exampleArray every iteration therrefore I dont need to clear the array.正如 Azro 指出的那样,我每次迭代都从 exampleArray 创建一个新变量,因此我不需要清除数组。

In Python, a list assignment refers to the same (original) instance of the list.在 Python 中,列表分配指的是列表的相同(原始)实例。 When you clear the local array, you are clearing both the local array and the one you think you copied into the object (but actually didn't), since these are in fact the same array.当您清除本地数组时,您同时清除了本地数组和您认为复制到 object 中的数组(但实际上没有),因为它们实际上是同一个数组。

Simple example:简单的例子:

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

To assign / copy an array as a separate object, you need to use a copy or deep copy operation.要将数组分配/复制为单独的 object,您需要使用复制或深复制操作。 A simple way in your current code would be a slice-to-copy:当前代码中的一种简单方法是切片复制:

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

Note the [:] added.注意添加的[:]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM