Skip to content

Instantly share code, notes, and snippets.

@xoxwgys56
Last active December 12, 2023 04:43
Show Gist options
  • Save xoxwgys56/4e7225d671eb4235b4cc83650a716e1f to your computer and use it in GitHub Desktop.
Save xoxwgys56/4e7225d671eb4235b4cc83650a716e1f to your computer and use it in GitHub Desktop.
Python MRO
class Human:
def say(self):
print("Hello")
class Mother(Human):
def say(self):
print("Mother")
class Father(Human):
def say(self):
print("Father")
class Son(Father, Mother):
pass
class Daughter(Mother, Father):
pass
if __name__ == "__main__":
print(Son.__mro__)
"""
First printed object is high priority
(
<class '__main__.Son'>, # not implemented
<class '__main__.Father'>, # <- implemented
<class '__main__.Mother'>,
<class '__main__.Human'>,
<class 'object'>
)
"""
"""
Left inheritance is first
"""
Son().say() # Father
Daughter().say() # Mother
class Human:
pass
class Mother(Human):
pass
class Father(Human):
pass
class Son(Human, Father, Mother):
pass
class Daughter(Mother, Father):
pass
if __name__ == "__main__":
"""Describe mixed priority"""
# No code described
"""
Traceback (most recent call last):
File "~/python-mro/main.py", line 15, in <module>
class Son(Human, Father, Mother):
TypeError: Cannot create a consistent method resolution
order (MRO) for bases Human, Father, Mother
"""
pass
class Human:
def say(self):
print("Hello")
class Mother(Human):
def say(self):
super().say() # NOTE: use inherited method
class Father(Human):
def say(self):
print("Father")
class Son(Father, Mother):
pass
class Daughter(Mother, Father):
pass
if __name__ == "__main__":
"""Describe priority when multiple inheritance"""
Son().say() # Father
Daughter().say() # Father
print(Son.__mro__)
"""
(
<class '__main__.Son'>, # not implemented
<class '__main__.Father'>, # <- implemented
<class '__main__.Mother'>,
<class '__main__.Human'>,
<class 'object'>
)
"""
print(Daughter.__mro__)
"""
(
<class '__main__.Daughter'>, # not implemented
<class '__main__.Mother'>, # not implemented
<class '__main__.Father'>, # <- implemented
<class '__main__.Human'>,
<class 'object'>
)
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment