Code Explanation:
1. Class Definition
class Demo:
items = []
This defines a class named Demo.
items is a class variable, not an instance variable.
Class variables are shared by all objects (instances) of the class.
So there is only one items list in memory for the entire class.
2. Creating First Object
d1 = Demo()
This creates an object d1 of class Demo.
d1 does not get its own items list.
Instead, d1.items refers to the same class-level list Demo.items.
3. Creating Second Object
d2 = Demo()
This creates another object d2.
Just like d1, d2.items also refers to the same shared list Demo.items.
4. Modifying the List Using d1
d1.items.append(1)
This appends 1 to the shared items list.
Since the list is shared, the change affects all instances of the class.
Internally, the list now becomes:
items = [1]
5. Printing Using d2
print(d2.items)
d2.items points to the same list that was modified using d1.
Therefore, it prints:
[1]
6. Final Output
[1]

0 Comments:
Post a Comment