Skip to content

Instantly share code, notes, and snippets.

@agagniere
Last active December 9, 2022 14:28
Show Gist options
  • Save agagniere/66090949d3347bc7d8492952d1902e41 to your computer and use it in GitHub Desktop.
Save agagniere/66090949d3347bc7d8492952d1902e41 to your computer and use it in GitHub Desktop.
Simple Point Class
class Point:
def __init__(self, x, y): self.x, self.y = x, y
def taxi_distance(self, other): return abs(self.x - other[0]) + abs(self.y - other[1])
def distance(self, other): return math.sqrt((self.x - other[0]) ** 2 + (self.y - other[1]) ** 2)
def module(self): return self.distance((0, 0))
def __add__(self, other): return Point(self.x + other[0], self.y + other[1])
def __radd__(self, other): return self + other
def __sub__(self, other): return Point(self.x - other[0], self.y - other[1])
def __neg__(self): return Point(-self.x, -self.y)
def __mul__(self, scalar): return Point(self.x * scalar, self.y * scalar)
def __rmul__(self, scalar): return self * scalar
def __eq__(self, other): return self.x == other[0] and self.y == other[1]
def __getitem__(self, i): return self.x if i == 0 else self.y
def __str__(self): return "({}, {})".format(self.x, self.y)
def __repr__(self): return "({} {})".format(self.x, self.y)
def __hash__(self): return (self.x, self.y).__hash__()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment