Code Explanation:
1. Defining Class A
class A:
def f(self): return "A"
Class A defines a method f.
f() returns the string "A".
2. Defining Class B
class B:
def f(self): return "B"
Class B also defines a method f.
f() returns the string "B".
3. Defining Class C Inheriting from A
class C(A): pass
Class C inherits from A.
At this point, the inheritance chain is:
C → A → object
4. Creating an Object of C
obj = C()
An instance obj of class C is created.
At this moment:
obj.f() → "A"
5. Changing the Base Class at Runtime
C.__bases__ = (B,)
This line modifies the inheritance of class C at runtime.
Now, C no longer inherits from A, but from B.
The new inheritance chain becomes:
C → B → object
Important:
This change affects all instances of C, including ones already created.
6. Calling f() After Base Change
print(obj.f())
Step-by-step method lookup:
Python looks for f in class C → not found.
Python looks in B (new base class) → found.
B.f() is called.
7. Final Output
B
Final Answer
✔ Output:
B

0 Comments:
Post a Comment