-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstep14.py
101 lines (82 loc) · 2.55 KB
/
step14.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
from __future__ import annotations
import json
import typing as t
class Person:
mother: t.Optional[Person]
father: t.Optional[Person]
def __init__(
self,
name: str,
mother: t.Optional[Person] = None,
father: t.Optional[Person] = None,
) -> None:
self.name = name
self.mother = mother
self.father = father
def __repr__(self: Person) -> str:
return self.name
@property
def json(self: Person) -> t.Dict[str, t.Optional[str]]:
return {
"name": self.name,
"mother": (
self.mother.name if self.mother else None
),
"father": (
self.father.name if self.father else None
),
"maternal_grandmother": (
self.mother.mother.name
if self.mother and self.mother.mother
else None
),
}
@property
def grandparents(self: Person) -> t.List[Person]:
grandparents = []
if self.mother:
grandparents.append(self.mother.mother)
grandparents.append(self.mother.father)
if self.father:
grandparents.append(self.father.mother)
grandparents.append(self.father.father)
return [
person
for person in grandparents
if person is not None
]
jobal = Person("Jobal Naberrie")
ruwee = Person("Ruwee Naberrie")
padme = Person("Padme Amidala", mother=jobal, father=ruwee)
shmi = Person("Shmi Skywalker Lars")
force = Person("The Force")
anakin = Person("Anakin Skywalker", mother=shmi, father=force)
luke = Person("Luke Skywalker", mother=padme, father=anakin)
leia = Person("Leia Organa", mother=padme, father=anakin)
han = Person("Han Solo")
kylo = Person("Kylo Ren", mother=leia, father=han)
def test_person() -> None:
foo = Person("foo")
assert f"{foo}" == "foo"
assert foo.name == "foo"
def test_json() -> None:
assert (
json.dumps(han.json) == "{"
'"name": "Han Solo", '
'"mother": null, '
'"father": null, '
'"maternal_grandmother": null'
"}"
)
assert (
json.dumps(luke.json) == "{"
'"name": "Luke Skywalker", '
'"mother": "Padme Amidala", '
'"father": "Anakin Skywalker", '
'"maternal_grandmother": "Jobal Naberrie"'
"}"
)
def test_grandparents() -> None:
assert luke.grandparents == [jobal, ruwee, shmi, force]
assert han.grandparents == []
assert kylo.grandparents == [padme, anakin]