I want to call a class attribute and append it to a list. Here is a simple script:
class class_1():
def __init__(self):
self.x = np.array([0, 0])
def update(self):
self.x += 1
return self.x
cl_1 = class_1()
a = []
for i in range(3):
y = cl_1.update()
print(y)
a.append(y)
print(a)
# output:
[1 1]
[2 2]
[3 3]
[array([3, 3]), array([3, 3]), array([3, 3])]
but I expect [array([1, 1]), array([2, 2]), array([3, 3])] as the final value of list a. I checked that there is no problem with python numbers:
class class_2():
def __init__(self):
self.x = 0
def update(self):
self.x += 1
return self.x
cl_2 = class_2()
a = []
for i in range(3):
y = cl_2.update()
print(y)
a.append(y)
print(a)
#output
1
2
3
[1, 2, 3]
return self.x.copy()to avoid the problem.self.x = self.x + 1.