Skip to content

Commit d1882e6

Browse files
committed
Add generics-exercise1.py: demonstrate generic types with Person class
- Create Person dataclass with @DataClass(frozen=True) decorator - Use List["Person"] generic type for children attribute (self-referencing) - Implement age() method that calculates age from date_of_birth - Add example Person instances: fatma, aisha, and imran - Implement print_family_tree() function to display family hierarchy - Demonstrate practical use of generics for type-safe collections - Show how mypy validates generic type parameters
1 parent ffc50f6 commit d1882e6

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

prep/generics-exercise1.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from dataclasses import dataclass
2+
from typing import List
3+
from datetime import date
4+
5+
@dataclass(frozen=True)
6+
class Person:
7+
name: str
8+
date_of_birth: date
9+
children: List["Person"]
10+
11+
def age(self) -> int:
12+
today = date.today()
13+
age = today.year - self.date_of_birth.year
14+
if (today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day):
15+
age -= 1
16+
return age
17+
18+
fatma = Person(name="Fatma", date_of_birth=date(2015, 7, 22), children=[])
19+
aisha = Person(name="Aisha", date_of_birth=date(2018, 3, 10), children=[])
20+
21+
imran = Person(name="Imran", date_of_birth=date(1985, 5, 15), children=[fatma, aisha])
22+
23+
def print_family_tree(person: Person) -> None:
24+
print(person.name)
25+
for child in person.children:
26+
print(f"- {child.name} ({child.age()})")
27+
28+
print_family_tree(imran)
29+
30+

0 commit comments

Comments
 (0)