Code Explanation:
1. Defining the Base Class
class Base:
A class named Base is defined.
This class will act as a parent class for other classes.
2. Defining __init_subclass__
def __init_subclass__(cls):
cls.tag = cls.__name__.lower()
__init_subclass__ is a special hook method.
Python automatically calls it every time a subclass of Base is created.
cls refers to the new subclass, not Base.
3. Creating Subclass A
class A(Base): pass
What happens internally:
Python creates the class A.
Because A inherits from Base, Python calls:
Base.__init_subclass__(A)
Inside the method:
cls.__name__ → "A"
"A".lower() → "a"
A.tag = "a" is created.
4. Creating Subclass B
class B(Base): pass
What happens internally:
Python creates the class B.
Because B inherits from Base, Python calls:
Base.__init_subclass__(B)
Inside the method:
cls.__name__ → "B"
"B".lower() → "b"
B.tag = "b" is created.
5. Printing the Values
print(A.tag, B.tag)
A.tag → "a"
B.tag → "b"
6. Final Output
a b
✅ Final Answer
✔ Output:
a b

0 Comments:
Post a Comment