I'm facing a nearly-textbook diamond inheritance problem. The (rather artificial!) example below captures all its essential features:
# CAVEAT: error-checking omitted for simplicity
class top(object):
def __init__(self, matrix):
self.matrix = matrix # matrix must be non-empty and rectangular!
def foo(self):
'''Sum all matrix entries.'''
return sum([sum(row) for row in self.matrix])
class middle_0(top):
def foo(self):
'''Sum all matrix entries along (wrap-around) diagonal.'''
matrix = self.matrix
n = len(matrix[0])
return sum([row[i % n] for i, row in enumerate(matrix)])
class middle_1(top):
def __init__(self, m, n):
data = range(m * n)
matrix = [[1 + data[i * n + j] for j in range(n)] for i in range(m)]
super(middle_1, self).__init__(matrix)
In summary, classes middle_0
and middle_1
are both subclasses of class top
, where middle_0
overrides method foo
and middle_1
overrides method __init__
. Basically, the classic diamond inheritance set up. The one elaboration on the basic pattern is that middle_1.__init__
actually invokes the parent class's __init__
. (The demo below shows these classes in action.)
I want to define a class bottom
that "gets"1 foo
from middle_0
and __init__
from middle_1
.
What's the "pythonic way" to implement such a bottom
class?
Demo:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print top(matrix).foo()
# 45
print middle_0(matrix).foo()
# 15
print middle_1(3, 3).foo()
# 45
# print bottom(3, 3).foo()
# 15
1I write "gets" instead of "inherits" because I suspect this problem can't be solved easily using standard Python inheritance.