Code Explanation:
1️⃣ Importing dataclass
from dataclasses import dataclass
Explanation
Imports the dataclass decorator.
It auto-generates methods like __init__, __repr__, etc.
2️⃣ Applying @dataclass
@dataclass
Explanation
Converts class A into a dataclass.
Automatically creates constructor like:
def __init__(self, x=[]):
self.x = x
⚠️ Important: x=[] is evaluated once, not per object.
3️⃣ Defining Class
class A:
Explanation
Defines class A.
4️⃣ Defining Attribute with Default Value
x: list = []
Explanation ⚠️ CRITICAL
x is given a default value of an empty list.
This list is shared across all instances.
๐ Only ONE list is created in memory.
5️⃣ Creating First Object
a1 = A()
Explanation
a1.x refers to the shared list.
6️⃣ Creating Second Object
a2 = A()
Explanation
a2.x refers to the same shared list.
๐ So:
a1.x is a2.x → True
7️⃣ Modifying List from a1
a1.x.append(1)
Explanation
Adds 1 to the shared list.
๐ Now shared list becomes:
[1]
8️⃣ Printing from a2
print(a2.x)
Explanation
Since a2.x points to the same list:
[1]
๐ค Final Output
[1]

0 Comments:
Post a Comment