我正在尝试使用协作多重继承模式来解决一个问题。我的python 2.7代码的一个非常简化的版本如下所示:
class Base1(object):
def __init__(self, a, b):
self.a = a
self.b = b
def to_tuple(self):
return self.a, self.b
def to_string(self):
return '%s.%s' % self.to_tuple() # (1)
class Base2(object):
def __init__(self, c, d):
self.c = c
self.d = d
def to_tuple(self):
return self.c, self.d
def to_string(self):
return '%s-%s' % self.to_tuple() #(2)
class MyMixin(Base1, Base2):
def __init__(self, a, b, c, d):
Base1.__init__(self, a, b)
Base2.__init__(self, c, d)
def to_tuple(self):
return Base1.to_tuple(self) + Base2.to_tuple(self)
def to_string(self):
return '{}: {} '.format(Base1.to_string(self), Base2.to_string(self))
mix = MyMixin('a', 'b', 'c', 'd')
print(mix.to_string())
在编写了这段代码之后,我期望得到以下结果:
a.b: c-d
但代码失败了。当运行#(1)
行时,self
是MyMixin
类,而不是Base1
类,因此to_tuple
返回4项。你知道吗
我发现解决这个问题的唯一方法是将上面的#(1)
和#(2)
行替换为:
return '%s.%s' % Base1.to_tuple() # (1)
return '%s.%s' % Base2.to_tuple() # (2)
这感觉非常错误,原因有很多。你知道吗
我做错什么了?你知道吗
下面是发生的事情。调用
mix.to_string()
时,首先,它调用Base1.to_string(self)
,将mix
实例作为self传递,这意味着在Base1上调用tou字符串时,它有一个MyMixin
实例,在to_tuple
调用时返回('a','b','c','d')。这就是它失败的原因,因为tuple包含4项,第1行只需要2项。你知道吗要解决此问题,请尝试避免从具有相同方法签名的多个类继承。用构图代替。你知道吗
相关问题 更多 >
编程相关推荐