附加到已实例化的numpy数组未更新

2024-05-28 18:54:59 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有下面的代码,我试图用新值附加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


Tags: 代码fromselfnumpyadd属性initdef
1条回答
网友
1楼 · 发布于 2024-05-28 18:54:59

如果将对象A发送到C而不是数组A到C,那么它仍然是连接的(在请求矩阵时一定要调用A.A而不是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.]]

相关问题 更多 >

    热门问题