我目前正在使用此模式创建一个继承自A和B的类C。我不能从C调用super().__init__,因为我必须在A和B中执行相同的操作,并且意外的参数会在顶层引起问题。我觉得这不是很优雅。在Python中进行多重继承的正确方式是什么?我猜查询mro来确定超类是否需要一个参数是不寻常的?
class A:
def __init__(self, something):
self.a = X(something)
def method_a(self):
self.a.go()
def method_ab(self):
self.a.go2()
class B:
def __init__(self, something):
self.b = X(something)
def method_b(self):
self.b.go()
def method_ab(self):
self.b.go2()
class C(A, B):
def __init__(self, something):
self.a_ = A(something)
self.b_ = B(something)
@property
def a(self):
return self.a_.a
@property
def b(self):
return self.b_.b
def method_ab(self):
for x in [self.a, self.b]:
x.method_ab()发布于 2013-07-12 17:59:37
我发现的最好的解决方案是使用基类来吸收额外的参数:
class Base:
def __init__(self, something):
pass
def method_ab(self):
pass
class A(Base):
def __init__(self, something):
super().__init__(something)
self.a = X(something)
def method_a(self):
self.a.go()
def method_ab(self):
super().method_ab()
self.a.go()
class B(Base):
def __init__(self, something):
super().__init__(something)
self.b = X(something)
def method_b(self):
self.b.go()
def method_ab(self):
super().method_ab()
self.b.go()
class C(A, B):
passhttps://stackoverflow.com/questions/17610269
复制相似问题