Clean up __add__ on Point; add __sub__

The dunder add method only ever had one overload, so you don't need to
declare an overload
This commit is contained in:
Eryn Wells 2023-02-12 19:44:28 -08:00
parent 7e00f58a40
commit 36206b5cc0

View file

@ -4,7 +4,7 @@
import math import math
from dataclasses import dataclass from dataclasses import dataclass
from typing import Any, Iterator, Optional, overload, Tuple from typing import Iterator, Optional, Tuple
@dataclass(frozen=True) @dataclass(frozen=True)
@ -36,6 +36,7 @@ class Point:
return (self.x in (other.x - 1, other.x + 1)) and (self.y in (other.y - 1, other.y + 1)) return (self.x in (other.x - 1, other.x + 1)) and (self.y in (other.y - 1, other.y + 1))
def direction_to_adjacent_point(self, other: 'Point') -> Optional['Vector']: def direction_to_adjacent_point(self, other: 'Point') -> Optional['Vector']:
'''Given a point directly adjacent to `self`'''
for direction in Direction.all(): for direction in Direction.all():
if (self + direction) != other: if (self + direction) != other:
continue continue
@ -47,15 +48,16 @@ class Point:
'''Compute the Euclidean distance to another Point''' '''Compute the Euclidean distance to another Point'''
return math.sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2) return math.sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2)
@overload
def __add__(self, other: 'Vector') -> 'Point': def __add__(self, other: 'Vector') -> 'Point':
...
def __add__(self, other: Any) -> 'Point':
if not isinstance(other, Vector): if not isinstance(other, Vector):
raise TypeError('Only Vector can be added to a Point') raise TypeError('Only Vector can be added to a Point')
return Point(self.x + other.dx, self.y + other.dy) return Point(self.x + other.dx, self.y + other.dy)
def __sub__(self, other: 'Vector') -> 'Point':
if not isinstance(other, Vector):
raise TypeError('Only Vector can be added to a Point')
return Point(self.x - other.dx, self.y - other.dy)
def __iter__(self): def __iter__(self):
yield self.x yield self.x
yield self.y yield self.y