This post is a follow up from . I’ll expand on the other common and deadly inheritance issue, i.e the diamond inheritance problem. This problem is often not seen in small programs, but is easily encountered when working in an OOP environment, and also is not very easily detected. If you’re seeing weird / unexpected results in an OOP program, this should be one of the highest priority check on your checklist !
Alright, so before explaining what diamond inheritance is, I would like to explain what is multiple inheritance. No multiple inheritance == No diamond inheritance issues ever encountered !
Multiple inheritance is when say you have one class (say
child), which is inheriting from two parent classes (say
Now to put the issue into perspective, let’s additionally say that both
father class are inheriting from a class
human. Thus both
father will derive some common methods from the
human class. Let’s say it’s the
eye_colour() (and only
eye_colour() for simplicity).
What about the
child class then ?
What should be the value of
child class ? Should it be taken from
mother class or should it be taken from
father class ?
The answer is – It’s language and implementation dependent.
For c++, this kind of a code will not even compile, and will force you to use some form of
virtual keyword in order to resolve your problem.
For Python, different versions have different Method Resolution Orders defined (MROs). In short it is a depth first search, so suppose if we use multiple inheritance in Python using:
class Child (Mother, Father):
Child class will get
Mother class’s function
Mother was inherited first and then
Father was inherited.
Similarly if we have declared
Child class as:
class Child (Father, Mother):
Child class will get
Father class’s function
Father was inherited first.
Kindly note that Python had several different algorithms for deciding the Method resolution in the past, so if you try it on older python versions, be sure to check what method resolution order did they use !
The above explanation for resolution is with reference to the MRO used with Python 3.
Note that Java doesn’t support multiple inheritance, and so this will never arise as an issue for the Java programmers 😉 .
Complete code for testing the Python’s method resolution order:
class Child(Mother, Father):
newborn = Child()
Try changing the order of
Father while inheriting and see the difference in output !
PS: If it isn’t evident from the name, the problem is called diamond problem simply because the shape that’s formed when you draw the inheritance tree on paper.
Similar to a diamond (if you’ve ever seen a diamond suite in a deck of cards :p ).
Thanks for reading !