Skip to content

Commit ffc50f6

Browse files
committed
Add dataclasses-exercise.py: Person class using @DataClass decorator
- Create Person class with @DataClass(frozen=True) decorator - Use datetime.date for date_of_birth instead of int for age - Replace manual __init__ with declarative field definitions - Implement is_adult() method with dynamic age calculation - Account for whether birthday has occurred this year - Add type hints for all attributes and methods - Include example usage with imran and eliza instances - Demonstrate immutable dataclass with frozen=True
1 parent 4876f0d commit ffc50f6

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

prep/dataclasses-exercise.py

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

0 commit comments

Comments
 (0)