Code Explanation:
1) class A:
Defines a new class A.
Inside this class, both class variables and methods will be defined.
2) val = 5
Declares a class variable val with value 5.
This belongs to the class itself, not to any specific object.
Accessible as A.val.
3) def __init__(self, v):
Defines the constructor of the class.
It runs automatically when you create a new object of class A.
Parameter v is passed during object creation.
4) self.val = v
This creates/overwrites an instance variable val on the object itself.
Instance variables take precedence over class variables when accessed through the object.
So now, self.val (object’s variable) will hide A.val (class variable) for that instance.
5) a1 = A(10)
Creates object a1 of class A.
Calls __init__ with v = 10.
Inside __init__, a1.val = 10.
Now a1 has its own instance variable val = 10.
6) a2 = A(20)
Creates another object a2.
Calls __init__ with v = 20.
Inside __init__, a2.val = 20.
Now a2 has its own instance variable val = 20.
7) print(A.val, a1.val, a2.val)
A.val → accesses the class variable, still 5.
a1.val → accesses a1’s instance variable, which is 10.
a2.val → accesses a2’s instance variable, which is 20.
Final Output
5 10 20
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment