python - 在没有继承的情况下从另一个访问类属性?使用类数组作为输入

标签 python numpy

我有一个类:

class A():
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def method_A(self):
        return self.a

现在,我有另一个 B 类:

class B():

    def __init__(self, c,d):
        self.c = c
        self.d = d

    def method_B(self):
        # do computations with a and b from class A
        # return A.a * c

一个解决方案是让 B 从 A 继承,但这意味着它继承了 A 的所有属性,这是我不想要的。

例如它将是:

class B(A):
    def __init__(self,a,b,c,d)
        A().__init__(self,a,b)
        self.c = c
        self.d = d

所以,我必须用 def __init__(self,a,b,c,d) 初始化我的 B 类所有参数(来自 A 和 B),对吗?

有什么办法可以避免这种情况?并且仍然可以访问 A 类属性和方法吗?

------------ 更新 1 ---------------------------- ----------

根据答案更新。

我希望能够使用 A 类的数组作为 B 类的输入。

我试过:

import numpy as np

class B():

    def __init__(self, c, d, the_a):
        self.c = c
        self.d = d
        self.the_a = the_a


    def method_B(self):
         for i in self.the_a:
            return self.the_a[0][0].a * self.c

a = np.array([[A(2, 4), A(3,5)]])
b = B(4, 4, a)
print(b.method_B())

我收到:值 8 .

但显然我没有正确使用 method_B 中的循环。

我只使用 0 索引,但我想不通!

-------- 更新 2 ----------------------------

我快到了..

 def method_B(self):
     for idx, x in np.ndenumerate(self.the_a):

        self.the_a[idx].a = self.the_a[idx].a * self.c
        self.the_a[idx].b = self.the_a[idx].b * self.c

    return self.the_a

现在,它返回我 [[<__main__.A object at 0x7f165426c9b0> <__main__.A object at 0x7f165426c898>]] .

有没有办法像这样接收更新的数组:

np.array([[ A(8, 16), A(12,20)]])

最佳答案

你需要一个 A 的实例:

def method_B(self, the_a):
    return the_a.a * self.c

关于python - 在没有继承的情况下从另一个访问类属性?使用类数组作为输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41976847/

相关文章:

python - Numpy使用切片修改多个值二维数组

python - 在 C/C++ 中使用 Python 代码

python - 使用 numpy.save (和 savez)出现意外类型错误

python - 从 URL 打开获取 JSON

python - 如何使用 tf.keras 在 RNN 中应用层归一化?

Python 并行处理 - Linux 和 Windows 之间的不同行为

python - RabbitMQ、Pika和重连策略

python - 为什么放大绘图时 x 轴的时间存在差异

numpy - Object dtype dtype ('O' ) 没有本地 HDF5 等效项

python - Theano共享变量更新导致 `ValueError: length not known`