|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# multiple-inheritance-3.py |
| 4 | + |
| 5 | +# Python supports multiple inheritance |
| 6 | +# and uses a depth-first order when searching for methods. |
| 7 | +# This search pattern is call MRO (Method Resolution Order) |
| 8 | + |
| 9 | +# Example for "Diamond Shape" inheritance |
| 10 | +# Lookup can get complicated when multiple classes inherit |
| 11 | +# from multiple parent classes. |
| 12 | + |
| 13 | +# In order to avoid ambiguity while doing a lookup for a method |
| 14 | +# in various classes, from Python 2.3, the MRO lookup order has an |
| 15 | +# additional feature. |
| 16 | + |
| 17 | +# It still does a depth-first lookup, but if the occurrence of a class |
| 18 | +# happens multiple times in the MRO path, it removes the initial occurrence |
| 19 | +# and keeps the latter. |
| 20 | + |
| 21 | +# In the example below, class `D` inherits from `B` and `C`. |
| 22 | +# And both `B` and `C` inherits from `A`. |
| 23 | +# Both `A` and `C` has the method `dothis()`. |
| 24 | + |
| 25 | +# We instantiate `D` and requests the 'dothis()' method. |
| 26 | +# By default, the lookup should go D -> B -> A -> C -> A. |
| 27 | +# But from Python 2.3, in order to reduce the lookup time, |
| 28 | +# the MRO skips the classes which occur multiple times in the path. |
| 29 | + |
| 30 | +# Hence the lookup will be D -> B -> C -> A. |
| 31 | + |
| 32 | + |
| 33 | +class A(object): |
| 34 | + def dothis(self): |
| 35 | + print("doing this in A") |
| 36 | + |
| 37 | + |
| 38 | +class B(A): |
| 39 | + pass |
| 40 | + |
| 41 | + |
| 42 | +class C(A): |
| 43 | + def dothis(self): |
| 44 | + print("doing this in C") |
| 45 | + |
| 46 | + |
| 47 | +class D(B, C): |
| 48 | + pass |
| 49 | + |
| 50 | + |
| 51 | +d_instance = D() |
| 52 | +d_instance.dothis() |
| 53 | + |
| 54 | +print("\nPrint the Method Resolution Order") |
| 55 | +print(D.mro()) |
| 56 | + |
| 57 | +''' |
| 58 | +O/P- |
| 59 | +doing this in C |
| 60 | +
|
| 61 | +Print the Method Resolution Order |
| 62 | +[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>] |
| 63 | +''' |
0 commit comments