Skip to content

Instantly share code, notes, and snippets.

@luizomf
Created August 9, 2022 10:59
Show Gist options
  • Save luizomf/8ca5d63a5f5f5b70b5460431c315aea3 to your computer and use it in GitHub Desktop.
Save luizomf/8ca5d63a5f5f5b70b5460431c315aea3 to your computer and use it in GitHub Desktop.
Implementação dos métodos mágicos para matemática em Python.
class Point:
"""
>>> p1 = Point(8, 6)
>>> p2 = Point(2, 3)
>>> p1 + p2
Point(10, 9)
>>> p1 - p2
Point(6, 3)
>>> p1 / p2
Point(4.0, 2.0)
>>> p1 * p2
Point(16, 18)
"""
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f'Point({self.x!r}, {self.y!r})'
def __add__(self, o):
x = self.x + o.x
y = self.y + o.y
return Point(x, y)
def __sub__(self, o):
x = self.x - o.x
y = self.y - o.y
return Point(x, y)
def __truediv__(self, o):
x = self.x / o.x
y = self.y / o.y
return Point(x, y)
def __mul__(self, o):
x = self.x * o.x
y = self.y * o.y
return Point(x, y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment