我有一个类:
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/