Code Explanation:
1. Defining Class A
class A:
data = []
Explanation:
class A: creates a class named A
data = [] defines a class variable named data.
It is an empty list.
Class variables are shared by the class and its subclasses unless overridden.
So initially:
A.data → []
2. Defining Subclass B
class B(A):
pass
Explanation:
class B(A): means B inherits from class A.
pass means no new attributes or methods are added.
Since B does not define its own data, it inherits data from A.
So:
B.data → refers to A.data
3. Defining Subclass C
class C(A):
data = []
Explanation:
class C(A): means C also inherits from class A.
But here data = [] creates a new class variable inside C.
This overrides the inherited variable from A.
So now:
A.data → []
B.data → refers to A.data
C.data → [] (separate list)
4. Modifying B.data
B.data.append(1)
Explanation:
B.data refers to A.data because B inherited it.
.append(1) adds 1 to the list.
Since B and A share the same list, the change affects both.
After this operation:
A.data → [1]
B.data → [1]
But:
C.data → []
because C has its own separate list.
5. Printing the Values
print(A.data, B.data, C.data)
Explanation:
A.data → [1]
B.data → [1] (same list as A)
C.data → [] (different list)
6. Final Output
[1] [1] []
Key Concept
Class Variable Inheritance
Class data value Reason
A [1] Original list modified
B [1] Inherited from A
C [] Overridden with its own list
✅ Final Output
[1] [1] []

0 Comments:
Post a Comment