附加到已经实例化的numpy数组不会更新

时间:2018-01-31 20:58:04

标签: python arrays numpy

假设我有以下代码,我试图用新值附加一个numpy数组。由于数组已经实例化为另一个类,因此在一个类中追加现有数组不会更新另一个类。

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()

输出:

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.]]

请帮助我,如何在更新A类中的属性A后更新C类中的属性A.

1 个答案:

答案 0 :(得分:1)

如果你将对象A发送到C而不是数组AA到C,它仍然是连接的(当要求矩阵时一定要调用AA而不是A)(我知道这很令人困惑,但只需检查代码你会明白的)

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()

打印:

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.]]