Code Expalnation:
1. Class Definition
class Test:
This line defines a class named Test.
A class is a blueprint for creating objects.
2. Class Variable
x = []
x is a class variable, not an instance variable.
It is created once and shared by all objects of the class.
Every instance of Test will refer to the same list x.
3. Method Definition
def add(self, val):
This defines a method named add.
self refers to the object that calls the method.
val is the value to be added.
4. Appending to the List
self.x.append(val)
self.x refers to the class variable x (since no instance variable named x exists).
append(val) adds val to the shared list.
5. Object Creation
a = Test()
b = Test()
Two separate objects a and b are created.
Important: Both objects share the same class variable x.
6. Method Call on Object a
a.add(1)
Calls add using object a.
1 is appended to the shared list x.
Now x = [1]
7. Method Call on Object b
b.add(2)
Calls add using object b.
2 is appended to the same shared list.
Now x = [1, 2]
8. Print Statement
print(a.x, b.x)
a.x and b.x both point to the same list.
Output:
[1, 2] [1, 2]

0 Comments:
Post a Comment