[Tutor] Clarity about MRO (method resolution order )
Manprit Singh
manpritsinghece at gmail.com
Fri Nov 26 20:30:37 EST 2021
Dear sir,
Consider the code given below :
class ABC:
def show(self):
print("HELLO")
class ABCD(ABC):
def show(self):
print("hello")
class ABCDE(ABC):
def show(self):
print("Hello")
class ABC12(ABCD, ABCDE):
pass
obj = ABC12()
obj.show() # gives the output hello
Just need to make myself clear about the output i got after executing this
code
The classes ABC, ABCD, ABCDE all have a method with the same name show().
obj is the instance of class ABC12. executing obj.show() will execute the
show ()
of ABCD class, the answer lies with the MRO of ABC12 class
ABC12.mro() will result in
[__main__.ABC12, __main__.ABCD, __main__.ABCDE, __main__.ABC, object]
According to this MRO, show() will be searched in the classes in the order
given in the output of ABC12.mro(). show() was first searched in ABC12 class,
it was not there , and hence it was searched in ABCD class, it was present
and hence executed.
Am I right with this explanation ?
More information about the Tutor
mailing list