Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@gwy15

gwy15/676315.py Secret

Last active May 28, 2020 07:18
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 gwy15/2149af5dfc325cfe95eccf23e4997365 to your computer and use it in GitHub Desktop.
Save gwy15/2149af5dfc325cfe95eccf23e4997365 to your computer and use it in GitHub Desktop.
import unittest
from typing import Tuple, Union, Callable
Vec2D = Tuple[int, int]
Vec2DF = Callable[[], Vec2D]
class Point:
def __init__(self, cord: Union[Vec2D, Vec2DF]):
self._cord = cord
def __add__(self, rhs: 'Point') -> 'Point':
return Point(
lambda: (self.x + rhs.x, self.y + rhs.y)
)
@property
def cord(self) -> Vec2D:
if isinstance(self._cord, Tuple):
return self._cord
else:
return self._cord()
@property
def x(self) -> int:
return self.cord[0]
@x.setter
def x(self, value: int):
self._cord = (value, self.y)
@property
def y(self) -> int:
return self.cord[1]
@y.setter
def y(self, value: int):
self._cord = (self.x, value)
class TestPoint(unittest.TestCase):
def test(self):
p1 = Point((1, 2))
p2 = Point((3, 4))
self.assertEqual(p1.x, 1)
self.assertEqual(p1.y, 2)
p_sum = p1 + p2
self.assertEqual(p_sum.x, 4)
self.assertEqual(p_sum.y, 6)
p1.x = 10
self.assertEqual(p_sum.x, 13)
# chained
p_sum2 = p_sum + p1 + p2
self.assertEqual(p_sum2.x, p1.x*2 + p2.x*2)
p2.x = 100
self.assertEqual(p_sum2.x, p1.x*2 + p2.x*2)
if __name__ == "__main__":
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment