Code Explanation:
1. Class Definition Begins
class Demo:
A new class named Demo is created.
This class will contain attributes and methods.
2. Class-Level Attribute
nums = []
nums is a class variable (shared by all objects of the class).
It is an empty list [] initially.
Any object of Demo will use this same list unless overridden.
3. Method Definition
def add(self, val):
self.nums.append(val)
The method add() takes self (object) and a value val.
It appends val to self.nums.
Since nums is a class list, appending through any object affects the same list.
4. Creating First Object
d1 = Demo()
Creates object d1 of class Demo.
d1 does not have its own nums; it uses the shared class list.
5. Creating Second Object
d2 = Demo()
Creates another object d2.
d2 also uses the same class-level list nums as d1.
6. Adding a Number Using d1
d1.add(4)
Calls the add() method on d1.
This executes self.nums.append(4).
Since nums is shared, the list becomes:
[4]
7. Printing Length of nums from d2
print(len(d2.nums))
d2 looks at the same shared list.
That list contains one element: 4
So length is:
1
Final Output:
1


0 Comments:
Post a Comment