Reputation: 626
Let say I have the following code, where I am trying to append a numpy array with new values. Since the array is already instantiated to another class, appending to the existing array in one class doesn't update the other.
import numpy as np
class A:
def __init__(self):
self.A = []
def init(self):
self.A = np.zeros((1, 5))
def add_items(self, item):
# np.append(self.A, item)
self.A = np.vstack([self.A, item])
print "from class A"
print self.A
class B:
def __init__(self):
self.A = A()
self.C = C()
def init(self):
self.A.init()
self.C.init(self.A.A)
class C:
def __init__(self):
self.A = []
def init(self, A):
self.A = A
def disp(self):
print "from class C"
print self.A
if __name__ == '__main__':
b = B()
b.init()
b.C.disp()
b.A.add_items(np.ones((1, 5)))
b.C.disp()
output:
from class C
[[ 0. 0. 0. 0. 0.]]
from class A
[[ 0. 0. 0. 0. 0.]
[ 1. 1. 1. 1. 1.]]
from class C
[[ 0. 0. 0. 0. 0.]]
please help me, how can I update the attribute A in class C after the attribute A in class A is updated.
Upvotes: 0
Views: 40
Reputation: 3648
If you send the object A to C instead of the array A.A to C, it still is connected (be sure to call A.A instead of A when asking for the matrix) (I know this is confusing, but just check the code and you'll understand)
import numpy as np
class A:
def __init__(self):
self.A = []
def init(self):
self.A = np.zeros((1, 5))
def add_items(self, item):
# np.append(self.A, item)
self.A = np.vstack([self.A, item])
print "from class A"
print self.A
class B:
def __init__(self):
self.A = A()
self.C = C()
def init(self):
self.A.init()
# send self.A instead of self.A.A
self.C.init(self.A)
class C:
def __init__(self):
self.A = []
def init(self, A):
self.A = A
def disp(self):
print "from class C"
# now as self.A is an object, and you want the array, return self.A.A
print self.A.A
if __name__ == '__main__':
b = B()
b.init()
b.C.disp()
b.A.add_items(np.ones((1, 5)))
b.C.disp()
this prints:
from class C
[[ 0. 0. 0. 0. 0.]]
from class A
[[ 0. 0. 0. 0. 0.]
[ 1. 1. 1. 1. 1.]]
from class C
[[ 0. 0. 0. 0. 0.]
[ 1. 1. 1. 1. 1.]]
Upvotes: 1