Skip to content

Commit 49fae75

Browse files
committed
add dataclasses exercise
1 parent 405f2c4 commit 49fae75

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

sprint-5/dataclasses_exercise.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from dataclasses import dataclass
2+
from datetime import date
3+
# exercise
4+
# Write a Person class using @datatype which uses a datetime.date for date of birth, rather than an int for age.
5+
# Re-add the is_adult method to it.
6+
7+
8+
@dataclass(frozen=True)
9+
class Person:
10+
name: str
11+
date_of_birth: date
12+
preferred_operating_system: str
13+
14+
def is_adult(self) -> bool:
15+
today = date.today()
16+
age = today.year - self.date_of_birth.year
17+
18+
if(today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day):
19+
age -= 1
20+
return age >= 18
21+
22+
imran = Person("Imran", date(2000, 1, 1), "Ubuntu")
23+
imran2 = Person("Imran", date(2000, 1, 1), "Ubuntu")
24+
print(imran.is_adult())
25+
print(imran == imran2) # True, because dataclasses automatically generate an __eq__ method that compares the fields of the dataclass.

0 commit comments

Comments
 (0)