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 decorator
1from dataclasses import dataclass
2
# @dataclass generates __init__, __repr__ and __eq__ from the fields
3@dataclass
4class Point:
# Fields are declared with type annotations
5 x: int
6 y: int
7
# You can add your own methods as usual
8 def distance(self):
# Distance from the origin by the Pythagorean theorem
9 return (self.x ** 2 + self.y ** 2) ** 0.5
10
# The generated __init__ takes x and y in field order
11p = Point(3, 4)
# The generated __repr__ prints Point(x=3, y=4)
12print(f"Point: {p}")
# Call the custom method: the distance is 5.0
13print(f"Distance: {p.distance()}")

Output

Point: Point(x=3, y=4)
Distance: 5.0
Practice typing this code

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

More Python examples at level 4

← Python typing practice