Skip to content

Commit bb360b8

Browse files
committed
add mro
1 parent d6b10e3 commit bb360b8

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# What is a Method Resolution Order (MRO)?
2+
# MRO is the classes (Superclasses, subclasses) order that Python searches for
3+
# attributes or methods.
4+
# First Python searches for the methods or attributes in the class itself, then
5+
# it follows the order of inheritance.
6+
# Let's take an example:
7+
class Parent:
8+
9+
def who_I_am(self):
10+
return "I am the Parent"
11+
12+
13+
class Child1(Parent):
14+
15+
def who_I_am(self):
16+
return "I am Child1"
17+
18+
19+
class Child2(Parent):
20+
21+
def who_I_am(self):
22+
return "I am Child2"
23+
24+
25+
class GrandChild(Child1, Child2):
26+
27+
def who_I_am(self):
28+
return "I am the GrandChild"
29+
30+
31+
# To get the MRO we use the mro() method:
32+
# print(GrandChild.mro())
33+
34+
# That means if I want to execute the who_I_am(), if the object is created
35+
# from the GrandChild class, then Python will search the Grandchild class
36+
# first.
37+
38+
grand_child = GrandChild()
39+
# print(grand_child.who_I_am())
40+
41+
# That's why we should be extra careful when using multi-level inheritance,
42+
# because it may lead to undesirable results.

0 commit comments

Comments
 (0)