Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Filename: mro_attribute_demo.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- This script demonstrates the usage of the __mro__ attribute in Python, which stands for Method Resolution Order.
- It defines three classes: A, B, and C. Class C inherits from both classes A and B, showcasing multiple inheritance.
- Requirements:
- - Python 3.x
- Functions:
- - line(): A utility function to print divider lines for better readability.
- Usage:
- 1. Run the script using Python 3.x interpreter.
- 2. The script will print the method resolution order (__mro__) for classes A, B, and C.
- 3. It will also perform hasattr checks to verify if instances of classes A, B, and C have the __mro__ attribute.
- Additional Notes:
- - The __mro__ attribute provides insight into the sequence of classes that Python will search to resolve method calls in a class hierarchy.
- - Instances of classes do not inherit from 'type', hence they do not have the __mro__ attribute.
- - This script serves as a basic example to understand the method resolution order and multiple inheritance in Python.
- - It's recommended to run the script in an environment with Python 3.x installed to ensure compatibility.
- """
- class A: pass
- class B: pass
- class C(A, B): pass
- # Function to print divider lines
- def line():
- print("-" * 94)
- line()
- print("\n\t\t\t:: Explanation for A.__mro__ ::\n")
- line()
- print("A.__mro__ represents the method resolution order for class A.\n")
- print("- It shows the sequence of classes that Python will search to resolve method calls for class A.")
- print("- In this case, A.__mro__ is:\n\n\t", A.__mro__)
- print()
- line()
- print("\n\t\t\t:: Explanation for B.__mro__ ::\n")
- line()
- print("B.__mro__ represents the method resolution order for class B.\n")
- print("- It shows the sequence of classes that Python will search to resolve method calls for class B.")
- print("- In this case, B.__mro__ is:\n\n\t", B.__mro__)
- print()
- line()
- print("\n\t\t\t:: Explanation for C.__mro__ ::\n")
- line()
- print("C.__mro__ represents the method resolution order for class C.\n")
- print("- It shows the sequence of classes that Python will search to resolve method calls for class C.")
- print("- In this case, C.__mro__ is:\n\n\t", C.__mro__)
- print()
- a = A()
- b = B()
- c = C()
- line()
- print("\n\t\t\t:: Explanation for hasattr checks ::\n")
- line()
- print("The following assertions check if the objects have the __mro__ attribute.\n")
- print("\t\t\tFor instance a:", hasattr(a, '__mro__'))
- print("\t\t\tFor instance b:", hasattr(b, '__mro__'))
- print("\t\t\tFor instance c:", hasattr(c, '__mro__'))
- print("\nSince instances do not inherit from 'type', they do not have this attribute.\n")
- line()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement