Code Explanation:
1) from dataclasses import dataclass
Imports the dataclass decorator.
@dataclass auto-generates common methods for a class (e.g., __init__, __repr__, __eq__) from its fields.
2) @dataclass(slots=True)
Converts the following class into a dataclass and enables __slots__.
slots=True means the class will define __slots__ = ('x', 'y'), which:
Prevents creation of a per-instance __dict__ (memory-efficient).
Disallows adding new attributes dynamically (e.g., p.z = 3 would raise AttributeError).
Can make attribute access slightly faster.
3) class Point:
Declares a simple data container named Point.
4) x: int and y: int
Declare two dataclass fields: x and y, both annotated as int.
Type hints are for readability/type checkers; they’re not enforced at runtime by default.
5) Auto-generated __init__
Because of @dataclass, Python effectively creates:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
No need to write the constructor yourself.
6) p = Point(1, 2)
Instantiates Point using the generated __init__.
Sets p.x = 1 and p.y = 2.
7) Auto-generated __repr__
@dataclass also generates a readable string representation, roughly:
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
8) print(p)
Prints the instance using that auto-generated __repr__.
Output
Point(x=1, y=2)
Download Book - 500 Days Python Coding Challenges with Explanation


0 Comments:
Post a Comment