Code Explanation:
Step 1: Define the Base Class
class Base:
This creates a parent class named Base. Other classes can inherit its attributes and methods.
Step 2: Create a Class Attribute
x = 1
The class attribute x is initialized to 1.
Initially:
Base.x = 1
Step 3: Define __init_subclass__()
def __init_subclass__(cls):
Python automatically calls __init_subclass__() when a new class inherits from Base or from a subclass that inherits this method.
The parameter cls refers to the newly created subclass.
For example, when class A is created:
cls → A
Step 4: Update the Subclass Attribute
cls.x += 2
This is equivalent to:
cls.x = cls.x + 2
Python looks up the current value of cls.x, adds 2, and assigns the result to the subclass.
If the subclass does not have its own x, Python initially finds the inherited value.
Step 5: Create Class A
class A(Base): pass
Class A inherits from Base.
When A is created, Python automatically calls:
Base.__init_subclass__(A)
Initially, A inherits Base.x, which is 1.
So:
A.x = 1 + 2
A.x = 3
The augmented assignment creates an x attribute directly on A. It does not change Base.x.
Now:
Base.x = 1
A.x = 3
Step 6: Create Class B
class B(A): pass
Class B inherits from A.
The inherited __init_subclass__() method runs again, this time with cls referring to B.
Since B does not initially define its own x, Python finds A.x, which is 3.
Therefore:
B.x = 3 + 2
B.x = 5
Now each class has its own effective value:
Base.x = 1
A.x = 3
B.x = 5
Step 7: Print the Values
print(Base.x, A.x, B.x)
Python prints the three class attributes in order:
- Base.x → 1
- A.x → 3
- B.x → 5
Final output:
1 3 5
300 Days Python Coding Challenges with Explanation


0 Comments:
Post a Comment