-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathmultiple-inheritance-1.py
54 lines (33 loc) · 1.25 KB
/
multiple-inheritance-1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# multiple-inheritance-1.py
# Python supports multiple inheritance and uses a depth-first order
# when searching for methods.
# This search pattern is call MRO (Method Resolution Order)
# This is the first example, which shows the lookup of a common
# function named 'dothis()', which we'll continue in other examples.
# As per the MRO output, it starts in class D, then B, A, and lastly C.
# Both A and C contains 'dothis()'. Let's trace how the lookup happens.
# As per the MRO output, it starts in class D, then B, A, and lastly C.
# class `A` defines 'dothis()' and the search ends there. It doesn't go to C.
# The MRO will show the full resolution path even if the full path is
# not traversed.
# The method lookup flow in this case is : D -> B -> A -> C
class A(object):
def dothis(self):
print("doing this in A")
class B(A):
pass
class C(object):
def dothis(self):
print("doing this in C")
class D(B, C):
pass
d_instance = D()
d_instance.dothis() # <== This should print from class A.
print("\nPrint the Method Resolution Order")
print(D.mro())
'''
O/P-
doing this in A
Print the Method Resolution Order
[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.A'>, <class '__main__.C'>, <class 'object'>]
'''