Skip to content

Commit aad3e37

Browse files
committed
Change the Person class to take a date of birth
1 parent 8c9cd80 commit aad3e37

4 files changed

Lines changed: 44 additions & 2 deletions

File tree

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
class Person:
2+
def __init__(self, name: str):
3+
self.name = name
4+
5+
def get_name(person: Person) -> str:
6+
return person.name
7+
8+
def get_age(person: Person) -> int:
9+
return person.age
10+
# As I expected, mypy prints an error saying that Person has no attribute name,
11+
# because the age property does not exist in the Person class.

‎sprint5-prep-exercises/classesAndObjects.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,8 @@ def __init__(self, name: str, age: int, preferred_operating_system: str):
1010

1111
eliza = Person("Eliza", 34, "Arch Linux")
1212
print(eliza.name)
13-
print(eliza.address)
13+
print(eliza.address)
14+
15+
16+
# The error means that address doesn't exist in the Person class. We can only
17+
# access attributes that were defined in the class, such as name, age, and preferred_operating_system.

‎sprint5-prep-exercises/methods.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import datetime as dt
2+
from dataclasses import dataclass
3+
4+
5+
@dataclass
6+
class Person:
7+
name: str
8+
birthdate: dt.date
9+
preferred_operating_system: str
10+
11+
def is_adult(self) -> bool:
12+
today = dt.date.today()
13+
age = today.year - self.birthdate.year
14+
15+
if (today.month, today.day) < (self.birthdate.month, self.birthdate.day):
16+
age -= 1
17+
18+
return age >= 18
19+
20+
21+
imran = Person("Imran", dt.date(2000, 8, 6), "Ubuntu")
22+
23+
print(imran.is_adult())

‎sprint5-prep-exercises/typeAnnotations.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,8 @@ def format_pence_as_string(total_pence: int) -> str:
3232
total_pence = sum_balances(balances)
3333
total_string = format_pence_as_string(total_pence)
3434

35-
print(f"The bank accounts total {total_string}")
35+
print(f"The bank accounts total {total_string}")
36+
def is_adult(person: Person) -> bool:
37+
return person.age >= 18
38+
39+
print(is_adult(imran))

0 commit comments

Comments
 (0)