Dataclass in Python
Level 4208 keystrokes
This uses @dataclass decorator to automatically generate __init__, __repr__, and other methods for a class.
Python code
# Import the dataclass decorator1from dataclasses import dataclass2 # @dataclass generates __init__, __repr__ and __eq__ from the fields3@dataclass4class Point: # Fields are declared with type annotations5 x: int6 y: int7 # You can add your own methods as usual8 def distance(self): # Distance from the origin by the Pythagorean theorem9 return (self.x ** 2 + self.y ** 2) ** 0.510 # The generated __init__ takes x and y in field order11p = Point(3, 4)# The generated __repr__ prints Point(x=3, y=4)12print(f"Point: {p}")# Call the custom method: the distance is 5.013print(f"Distance: {p.distance()}")Output
Point: Point(x=3, y=4) Distance: 5.0
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
:× 6(× 6)× 6*× 6.× 4"× 4{× 2}× 2,× 1@× 1