Code Explanation:
1. Defining the first parent class
class One:
def f(self): return "one"
This defines a class One.
It has a method f() that returns the string "one".
2. Defining the second parent class
class Two:
def f(self): return "two"
This defines another class Two.
It also has a method f(), but it returns "two".
3. Defining the child class
class Test(One): pass
Test is a subclass of One.
It does not define any methods of its own.
Initially, Test inherits f() from One.
4. Creating an instance
t = Test()
An object t of class Test is created.
At this moment, t.f() would return "one".
5. Changing the base class dynamically
Test.__bases__ = (Two,)
__bases__ is a special attribute that stores a class’s parent classes.
This line replaces One with Two as the base class of Test.
Now:
class Test(Two): ...
This change affects all existing and future instances of Test.
6. Calling the method
print(t.f())
Python looks for f() using the Method Resolution Order (MRO):
Test
Two
f() is found in Two.
So "two" is returned.
✅ Final Output
two

0 Comments:
Post a Comment