Code Explanation:
1. Defining the Base Class
class Base:
A class named Base is defined.
It will control behavior of all its subclasses.
2. Overriding __init_subclass__
def __init_subclass__(cls):
cls.run = lambda self: cls.__name__
__init_subclass__ is called automatically whenever a subclass is created.
cls refers to the newly created subclass.
This line injects a new method run into the subclass.
run returns the subclass's class name (cls.__name__).
So every subclass of Base automatically gets a run() method.
3. Creating Subclass A
class A(Base): pass
A is created as a subclass of Base.
This triggers:
Base.__init_subclass__(A)
So A.run = lambda self: "A"
4. Creating Subclass B
class B(A): pass
B is created as a subclass of A.
Since A inherited __init_subclass__ from Base, it is called for B too:
Base.__init_subclass__(B)
So B.run = lambda self: "B"
5. Calling the Methods
print(A().run(), B().run())
Step-by-step:
A().run() returns "A".
B().run() returns "B".
print prints both.
6. Final Output
A B
Final Answer
✔ Output:
A B


0 Comments:
Post a Comment