Code Explanation:
1. Base Class Definition
class Base:
Defines a class named Base.
2. Defining __init_subclass__
def __init_subclass__(cls):
__init_subclass__ is a special class method.
It is automatically called whenever a subclass of Base is created.
cls refers to the newly created subclass (not the base class).
3. Setting a Class Attribute
cls.tag = cls.__name__.lower()
Sets a class attribute tag on the subclass.
cls.__name__ → name of the subclass as a string.
.lower() → converts it to lowercase.
So when subclasses are created:
class A(Base) → cls.__name__ is "A" → cls.tag = "a"
class B(Base) → cls.__name__ is "B" → cls.tag = "b"
4. Creating Subclass A
class A(Base): pass
Creates subclass A of Base.
Automatically triggers Base.__init_subclass__(A).
Sets A.tag = "a".
5. Creating Subclass B
class B(Base): pass
Creates subclass B of Base.
Automatically triggers Base.__init_subclass__(B).
Sets B.tag = "b".
6. Printing the Tags
print(A.tag, B.tag)
Prints the class attributes assigned during subclass creation.
7. Final Output
a b


0 Comments:
Post a Comment