Skip to content

Commit e9e8d65

Browse files
committed
Add dataclass example for Person with date_of_birth and is_adult method
1 parent 19d3bed commit e9e8d65

1 file changed

Lines changed: 23 additions & 0 deletions

File tree

‎dataclasses_.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from dataclasses import dataclass
2+
from datetime import date
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+
(today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day)
14+
)
15+
return age >= 18
16+
17+
18+
imran = Person("Imran", date(2002, 5, 15), "Ubuntu")
19+
imran2 = Person("Imran", date(2002, 5, 15), "Ubuntu")
20+
21+
print(imran) # Person(name='Imran', date_of_birth=datetime.date(2002, 5, 15), preferred_operating_system='Ubuntu')
22+
print(imran == imran2) # True
23+
print(imran.is_adult()) # True

0 commit comments

Comments
 (0)