我有一个带有一些属性字段的类,它是一个 numpy 数组。该类能够生成同一类的新实例。现在我的问题是所有实例 这样创建的似乎指向同一个字段属性。因此,当给定代码的预期输出是:
[0, 0]
[1, 0]
[0, 2]
它实际上给出了:
[1, 2]
[1, 2]
[1, 2]
当我随后更改a.field中的条目时,所有实例的字段属性中的条目都会更改
有人知道如何解决这个问题或者我在这里理解错误吗?
import numpy as np
class A:
def __init__(self, field=np.zeros(2)):
self.field=field
def setField(self, c, index):
if index<len(self.field):
self.field[index]=c
def multiply(self):
new_A=np.empty(2, dtype=object)
for n in range(0, 2, 1):
new_A[n]=A()
new_A[n].setField(n+1, n)
return new_A
a=A()
subs=a.multiply()
print a.field
print subs[0].field
print subs[1].field
最佳答案
您不应该将数组作为默认参数,而应该像这样定义它:
class A:
def __init__(self, field=None):
if field is None:
field = np.zeros(2)
self.field=field
def setField(self, c, index):
if index<len(self.field):
self.field[index]=c
def multiply(self):
new_A=np.empty(2, dtype=object)
for n in range(0, 2, 1):
new_A[n]=A()
new_A[n].setField(n+1, n)
return new_A
查看“Least Astonishment” in Python: The Mutable Default Argument有关为什么不应使用列表或数组作为默认参数的详细说明。
关于python - np.array 作为 Python 中属性的默认值被多个实例引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25849304/