Code Explanation:
1) Class definition + class variable
class A:
items = []
items is a class variable (shared by all instances of A).
Only one list object is created and stored on the class A.items.
2) First instance
a1 = A()
Creates an instance a1.
a1.items does not create a new list; it references A.items.
3) Second instance
a2 = A()
Creates another instance a2.
a2.items also references the same list A.items.
4) Mutate through one instance
a1.items.append(10)
You’re mutating the shared list (the class variable), not reassigning.
Since a1.items and a2.items both point to the same list object, the append is visible to both.
5) Observe from the other instance
print(a2.items)
Reads the same shared list; it now contains the appended value.
Output:
[10]
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment