I am trying to use inheritance in which I have a base class, say X
, and 2 classes which both independently inherit from X
, say A(X)
and B(x)
(these represent the common attributes of a whole bunch of tertiary classes, A1(A)
, A2(A)
, B1(B)
, etc.)
I then have some classes which ideally would inherit from both A
and B
, i.e., AB(A, B)
. Thus creating a “diamond-shaped” inheritance. But Python doesn’t seem to like this (see example below).
Why is this? Is this a bug? Does anyone know how to work around this? The example I have given is obviously extremely over-simplified, but I have a case in which I need to execute this sort of “diamond-shaped” inheritance, but it doesn’t seem to work.
I am using Python 3.11.6
For example, consider the following:
# main.py
class X:
def __init__(self, x):
self.x = x
class A(X):
def __init__(self, a, x):
self.a = a
super().__init__(x)
class B(X):
def __init__(self, b, x):
self.b = b
super().__init__(x)
class AB(A, B):
def __init__(self, a, b, x):
A.__init__(self, a, x)
B.__init__(self, b, x)
ab = AB("a", "b", "x")
This fails with the following exception:
Traceback (most recent call last):
File "main.py", line 28, in <module>
ab = AB("a", "b", "x")
^^^^^^^^^^^^^^^^^
File "main.py", line 24, in __init__
A.__init__(self, a, x)
File "main.py", line 11, in __init__
super().__init__(x)
TypeError: B.__init__() missing 1 required positional argument: 'x'
As you can see, the super()
inside A.__init__()
refers to B
, even though
issubclass(A, B) == False
johnstone.matt is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.