Skip to content

Instantly share code, notes, and snippets.

@MestreLion
Created October 18, 2021 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MestreLion/0937fd4f5044cb187b0c57220216ecf1 to your computer and use it in GitHub Desktop.
Save MestreLion/0937fd4f5044cb187b0c57220216ecf1 to your computer and use it in GitHub Desktop.
Website exercise
import operator
class Point:
"""A 3D, (x, y, z) mutable point
>>> p1 = Point(1, 2, 3)
>>> p1
Point(x=1, y=2, z=3)
>>> p2 = Point(1, 2, 3)
>>> p1 == p2
True
>>> p2.x = 4
>>> p1 == p2
False
>>> p2
Point(x=4, y=2, z=3)
Bonus 1
For the first bonus, I'd like you to allow Point objects to be added and subtracted from each other
>>> p1 = Point(1, 2, 3)
>>> p2 = Point(4, 5, 6)
>>> p1 + p2
Point(x=5, y=7, z=9)
>>> p3 = p2 - p1
>>> p3
Point(x=3, y=3, z=3)
Bonus 2
For the second bonus, I'd like you to allow Point objects to be scaled up and down by numbers
>>> p1 = Point(1, 2, 3)
>>> p2 = p1 * 2
>>> p2
Point(x=2, y=4, z=6)
>>> 3 * p1
Point(x=3, y=6, z=9)
Bonus 3
For the third bonus, I'd like you to allow Point objects to be unpacked using multiple assignment like this:
>>> p1 = Point(1, 2, 3)
>>> x, y, z = p1
>>> (x, y, z)
(1, 2, 3)
"""
def __init__(self, x, y, z):
self.x: float = x
self.y: float = y
self.z: float = z
def __iter__(self):
yield from vars(self).values()
def __eq__(self, other):
if not isinstance(other, self.__class__): raise NotImplementedError
return vars(self) == vars(other)
def __add__(self, other):
# Could also use the same approach as __sub__
if not isinstance(other, self.__class__): raise NotImplementedError
return self.__class__(*(map(sum, zip(self, other))))
def __sub__(self, other):
if not isinstance(other, self.__class__): raise NotImplementedError
return self.__class__(*(operator.sub(*_) for _ in zip(self, other)))
def __mul__(self, other):
if not isinstance(other, (int, float)): raise NotImplementedError
return self.__class__(*(_ * other for _ in self))
__rmul__ = __mul__
def __repr__(self):
sig = ", ".join(f"{k}={v}" for k, v in vars(self).items())
return self.__class__.__name__ + f"({sig})"
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment