Code Explanation:
1️⃣ Importing dataclass
from dataclasses import dataclass
Explanation
Imports the dataclass decorator.
It helps automatically generate methods like:
__init__
__repr__
__eq__
2️⃣ Applying @dataclass Decorator
@dataclass
Explanation
This decorator modifies class A.
Automatically adds useful methods.
Saves you from writing boilerplate code.
3️⃣ Defining the Class
class A:
Explanation
A class A is created.
It will hold data (like a structure).
4️⃣ Defining Attributes with Type Hints
x: int
y: int
Explanation
Defines two attributes:
x of type int
y of type int
These are used by @dataclass to generate constructor.
5️⃣ Auto-Generated Constructor
๐ Internally, Python creates:
def __init__(self, x, y):
self.x = x
self.y = y
Explanation
You don’t write this manually.
@dataclass creates it automatically.
6️⃣ Creating Object
a = A(1,2)
Explanation
Calls auto-generated __init__.
Assigns:
a.x = 1
a.y = 2
7️⃣ Printing Object
print(a)
Explanation
Calls auto-generated __repr__() method.
๐ Internally behaves like:
"A(x=1, y=2)"
๐ค Final Output
A(x=1, y=2)

0 Comments:
Post a Comment