Code Explanation:
1️⃣ Defining the Class
class A:
Explanation
A class named A is created.
This class will store a list in each object.
2️⃣ Constructor with Default Argument
def __init__(self, lst=[]):
Explanation ⚠️ (VERY IMPORTANT)
lst=[] is a default argument.
This list is created only once when the function is defined.
It is shared across all objects if no argument is passed.
3️⃣ Assigning List to Object
self.lst = lst
Explanation
Assigns the list to the object.
But since default list is shared → all objects point to same list.
4️⃣ Creating First Object
a1 = A()
Explanation
No argument passed → uses default list [].
Now:
a1.lst → []
5️⃣ Modifying List via First Object
a1.lst.append(1)
Explanation
Adds 1 to the list.
Since list is shared:
lst → [1]
6️⃣ Creating Second Object
a2 = A()
Explanation
Again no argument → uses SAME default list.
So:
a2.lst → [1]
7️⃣ Modifying List via Second Object
a2.lst.append(2)
Explanation
Adds 2 to the SAME shared list.
Now:
lst → [1, 2]
8️⃣ Printing the Result
print(a1.lst, a2.lst)
Explanation
Both objects refer to the same list.
๐ค Final Output
[1, 2] [1, 2]

0 Comments:
Post a Comment