Code Explanation:
1) from dataclasses import dataclass
Imports the dataclass decorator from Python’s dataclasses module.
dataclass automatically adds:
__init__ method
__repr__ method (nice string representation)
Optional comparison methods (__eq__, etc.)
2) @dataclass
@dataclass
class Point:
x: int
y: int = 0
Decorates the Point class to become a dataclass.
Python will automatically generate an __init__ method like:
def __init__(self, x, y=0):
self.x = x
self.y = y
And a __repr__ method like:
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
3) x: int and y: int = 0
These are type hints (int) for the fields.
y has a default value of 0 → optional during object creation.
x is required when creating a Point object.
4) p = Point(5)
Creates a new Point object.
Passes 5 for x.
y is not provided → uses default y=0.
5) print(p)
Prints the object using the auto-generated __repr__.
Output will be:
Point(x=5, y=0)
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment