MRO (Method Resolution Order)
most of codes are referenced from https://tibetsandfox.tistory.com/26
MRO (Method Resolution Order)
most of codes are referenced from https://tibetsandfox.tistory.com/26
| 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'> | |
| ) | |
| """ |