Code Explanation:
1. Class Definition
class Demo:
Explanation:
A class named Demo is created.
This class will hold data and behavior shared by its objects.
2. Class Variable
data = []
Explanation:
data is a class variable.
It is created once and shared by all objects of the class.
Since it is a list (mutable), changes made by one object affect all objects.
3. Method Definition
def add(self, x):
Explanation:
add() is an instance method.
self refers to the current object.
x is the value to be added to the list.
4. Modifying the Class Variable
self.data += [x]
Explanation:
self.data refers to the class variable data because no instance variable named data exists.
+= [x] modifies the same list object by adding x to it.
No new list is created; the shared list is updated.
5. Creating First Object
d1 = Demo()
Explanation:
An object d1 of class Demo is created.
It does not have its own data variable.
6. Creating Second Object
d2 = Demo()
Explanation:
Another object d2 of class Demo is created.
It also shares the same class variable data.
7. Calling Method Using First Object
d1.add(5)
Explanation:
The value 5 is added to the shared class list data.
Now data = [5] for all objects.
8. Accessing Data Using Second Object
print(d2.data)
Explanation:
d2.data accesses the same shared class variable.
Since d1 already modified it, d2 sees the updated list.
FINAL OUTPUT
[5]


0 Comments:
Post a Comment