Code Explanation:
๐น 1. Importing dataclass and replace
from dataclasses import dataclass, replace
✅ Explanation
dataclass and replace are imported from Python's built-in dataclasses module.
@dataclass automatically creates useful methods like:
__init__()
__repr__()
__eq__()
replace() creates a new object by copying an existing dataclass object and changing selected fields.
dataclasses Module
│
▼
┌───────────────┐
│ @dataclass │
│ replace() │
└───────────────┘
Nothing executes yet.
๐น 2. Creating a Dataclass
@dataclass
class User:
age: int
✅ Explanation
@dataclass converts the normal class into a dataclass.
Python automatically creates something similar to:
class User:
def __init__(self, age):
self.age = age
Current Memory
User Class
Field
age : int
No object is created yet.
๐น 3. Creating an Object
u = User(20)
✅ Explanation
An object named u is created.
Python automatically calls:
User(age=20)
Current Memory
u
▼
+------------+
| age = 20 |
+------------+
Visual Representation
User Object
age
20
๐น 4. Using replace()
replace(u, age=30)
✅ Explanation
replace() does not modify the original object.
Instead, it:
Copies the object.
Changes the specified field.
Returns a new object.
Current Memory
Original Object
u
age = 20
↓
replace()
↓
New Object
age = 30
Visual Representation
u
│
▼
+-----------+
| age = 20 |
+-----------+
│
replace(age=30)
▼
+-----------+
| age = 30 |
+-----------+
Notice
The original object is unchanged.
๐น 5. Accessing .age
replace(u, age=30).age
✅ Explanation
replace() returns a new object.
Python immediately accesses its age attribute.
Returned value
30
๐น 6. Printing the Result
print(replace(u, age=30).age)
✅ Explanation
Python prints the value of the age attribute from the new object.
Output
30
๐ฏ Final Output
30

0 Comments:
Post a Comment