Dataclass with distance in Python
Dataclasses cut the boilerplate out of small value classes.
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
def distance_to(self, other):
return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5
How it works
@dataclasswrites__init__and friends for free.- Stores
xandycoordinates. distance_toapplies the Pythagorean theorem between two points.
Keywords and builtins used here
Pointclassdefdistance_tofloatreturnself
The run, in numbers
- Lines
- 9
- Characters to type
- 173
- Tokens
- 53
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 32 seconds.
Step 4 of 4 in Typing & dataclasses, step 23 of 53 in Pythonic Python.