Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:新对象丢失数组属性_Python_Arrays_Reference - Fatal编程技术网

Python:新对象丢失数组属性

Python:新对象丢失数组属性,python,arrays,reference,Python,Arrays,Reference,我目前正在编写一个python程序,该程序应该创建一个类对象数组,这是a创建的 我面临的问题是,这个类有一个数组作为属性。执行myArray.clear()之后,类对象将丢失数组值。其他值不会丢失。我知道这是由于数组的引用造成的,但我不知道如何修复它 代码示例: a = [1, 2, 3] b = a a.append(4) print(b) # prints [1, 2, 3, 4] 课程 class Testclass(object): def __init__(self, arra

我目前正在编写一个python程序,该程序应该创建一个类对象数组,这是a创建的

我面临的问题是,这个类有一个数组作为属性。执行myArray.clear()之后,类对象将丢失数组值。其他值不会丢失。我知道这是由于数组的引用造成的,但我不知道如何修复它

代码示例:

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

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
因此,我想知道如何将对象添加到数组中,而不会在每次迭代后丢失值。 提前感谢!:)

编辑


正如Azro指出的,每次迭代我都会从exampleArray创建一个新变量,因为我不需要清除数组。

在Python中,列表赋值指的是列表的相同(原始)实例。清除本地数组时,您同时清除了本地数组和您认为复制到对象中的数组(但实际上没有),因为它们实际上是同一个数组

简单的例子:

a = [1, 2, 3]
b = a
a.append(4)
print(b)
# prints [1, 2, 3, 4]
要将数组作为单独的对象分配/复制,需要使用复制或深度复制操作。当前代码中的一种简单方法是复制一个片段:

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

注意添加的
[:]

为什么要使用clear?你清空了数组,这看起来很正常,只是不清除
就空了。或者执行
self.\u array=list(array)
tocopy@azro我清除数组是因为在我的主程序中,我将值添加到数组中,但对于对象,我只需要当前迭代中的值,并且因为我添加了值,所以我从之前的值中获得了值。也许有更好的办法?但是谢谢你的把戏成功了!您在每次迭代中创建
exampleArray
,您不会附加到它,所以没问题,只需删除清除行即可