Code Explanation:
1. Defining Class A
class A:
def f(self): return "A"
A class A is defined.
It has a method f() that returns "A".
2. Defining Class B
class B:
def f(self): return "B"
A class B is defined.
It also has a method f() but returns "B".
3. Defining Class C Inheriting from A
class C(A): pass
C initially inherits from A.
So normally:
C().f() → "A"
4. Changing the Base Class at Runtime
C.__bases__ = (B,)
This dynamically changes the inheritance of class C.
Now C no longer inherits from A, but from B.
So the new hierarchy is:
C → B → object
5. Calling f() on a C Object
print(C().f())
Step-by-step:
C() creates an instance of C.
f() is searched:
Not found in C
Found in B (new base class)
B.f() is called → returns "B".
6. Final Output
B
Final Answer
✔ Output:
B


0 Comments:
Post a Comment