-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathe_distance.py
50 lines (40 loc) · 1007 Bytes
/
e_distance.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# e_distance.py
# Generalizing distance() using protocols
from math import sqrt
from typing import Protocol
from attrs import field, frozen
class Coord(Protocol):
x: int
y: int
def distance(c1: Coord, c2: Coord) -> float:
return sqrt((c2.x - c1.x) ** 2 + (c2.y - c1.y) ** 2)
@frozen
class Point(Coord):
x: int
y: int
def test_pythagorean_triple():
assert distance(Point(3, 0), Point(0, 4)) == 5
# Suppose you are handed this non-Coord class:
@frozen
class AB:
a: int
b: int
def test_point_adapter():
ab1, ab2 = AB(3, 0), AB(0, 4)
# Point can be used as an adapter:
d = distance(Point(ab1.a, ab1.b), Point(ab2.a, ab2.b))
assert d == 5
# An adapter class:
@frozen
class Adapt(Coord):
ab: AB # Composition
x: int = field()
y: int = field()
@x.default
def dx(self):
return self.ab.a
@y.default
def dy(self):
return self.ab.b
def test_adapt_class():
assert distance(Adapt(AB(3, 0)), Adapt(AB(0, 4))) == 5