Skip to content

Commit ecab953

Browse files
Complete exercises for Module Tools/Sprint 5/Prep - step 6 'Generics'
1 parent 0d1af59 commit ecab953

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

prep-exercises/f_generics.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
from dataclasses import dataclass
2+
from typing import List, Optional
3+
4+
# @dataclass(frozen=True)
5+
# class Person:
6+
# name: str
7+
# children: List["Person"]
8+
9+
# fatma = Person(name="Fatma", children=[])
10+
# aisha = Person(name="Aisha", children=[])
11+
12+
# imran = Person(name="Imran", children=[fatma, aisha])
13+
14+
# def print_family_tree(person: Person) -> None:
15+
# print(person.name)
16+
# for child in person.children:
17+
# print(f"- {child.name} ({child.age})")
18+
19+
# print_family_tree(imran)
20+
21+
22+
# ------------------------
23+
# Exercise 1
24+
# ------------------------
25+
# Fix the above code so that it works. You must not change the print on line 17
26+
# - we do want to print the children’s ages. (Feel free to invent the ages of Imran’s children.)
27+
28+
@dataclass(frozen=True)
29+
class Person:
30+
name: str
31+
children: List["Person"]
32+
age: Optional[int] = None # add the optional import so that age is optional with a default of None
33+
34+
35+
fatma = Person(name="Fatma", age=13, children=[]) # order of arguments doesn't matter when named
36+
aisha = Person("Aisha", [], 8) #however it does if you don't strictly name them
37+
38+
imran = Person(name="Imran", children=[fatma, aisha])
39+
40+
def print_family_tree(person: Person) -> None:
41+
print(person.name)
42+
for child in person.children:
43+
print(f"- {child.name} ({child.age})")
44+
45+
print_family_tree(imran)

0 commit comments

Comments
 (0)