File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
03.OOP_Pillars/01.oop_pillar_scripts Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
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.
You can’t perform that action at this time.
0 commit comments