我有一个班级:
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)
所有参数(来自A和B)初始化我的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 ------------------------------ < / p>
我快到了..
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)]])
答案 0 :(得分:2)
您需要一个A:
的实例def method_B(self, the_a):
return the_a.a * self.c
答案 1 :(得分:2)
在B组中保存A类的实例。
class A():
def __init__(self, a, b):
self.a = a
self.b = b
def method_A(self):
return self.a
class B():
def __init__(self, c, d, the_a):
self.c = c
self.d = d
self.the_a = the_a
def method_B(self):
return self.the_a.a * self.c
a = A(1, 2)
b = B(3, 4, a)
答案 2 :(得分:2)
如果您创建A:
的实例,请按照上一个答案进行操作a = A(a, b)
然后,在B类中,您可以将该实例作为单个参数传入,并通过引用它的实例来访问任何方法(或该变量):
class B():
def __init__(self, c, d, instance_of_a):
self.c = c
self.f = d
self.e = instance_of_a.[the method or variable you want from class A]
希望这有帮助,