Skip to content

Commit 4876f0d

Browse files
committed
Add methods-exercise2.py: refactor Person class to use date_of_birth
- Replace age (int) parameter with date_of_birth (datetime.date) - Convert is_adult() from free function to instance method - Implement dynamic age calculation based on current date - Account for whether birthday has occurred this year - Add type hints for all parameters and return types - Include example usage with imran and eliza instances
1 parent 01fb96a commit 4876f0d

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

prep/methods-exercise2.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from datetime import date
2+
3+
class Person:
4+
def __init__(self, name: str, date_of_birth: date, preferred_operating_system: str):
5+
self.name = name
6+
self.date_of_birth = date_of_birth
7+
self.preferred_operating_system = preferred_operating_system
8+
9+
def is_adult(self) -> bool:
10+
today = date.today()
11+
age = today.year - self.date_of_birth.year
12+
13+
# Check if birthday has occurred this year
14+
if (today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day):
15+
age -= 1
16+
17+
return age >= 18
18+
19+
imran = Person("Imran", date(2002, 5, 15), "Ubuntu")
20+
print(imran.name)
21+
print(imran.is_adult())
22+
23+
eliza = Person("Eliza", date(1990, 3, 20), "Arch Linux")
24+
print(eliza.name)
25+
print(eliza.is_adult())

0 commit comments

Comments
 (0)