Skip to content

Commit 0d1af59

Browse files
Complete exercises for Module Tools/Sprint 5/Prep - step 5 'Dataclasses'
1 parent e85b923 commit 0d1af59

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

prep-exercises/e_dataclasses.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# class Person:
2+
# def __init__(self, name: str, age: int, preferred_operating_system: str):
3+
# self.name = name
4+
# self.age = age
5+
# self.preferred_operating_system = preferred_operating_system
6+
7+
# imran = Person("Imran", 22, "Ubuntu")
8+
# imran2 = Person("Imran", 22, "Ubuntu")
9+
10+
# print(imran == imran2) # Prints False
11+
# print(imran) # <__main__.Person object at 0x74b1986e2990>
12+
13+
from dataclasses import dataclass
14+
from datetime import date
15+
16+
# @dataclass(frozen=True)
17+
# class Person:
18+
# name: str
19+
# age: int
20+
# preferred_operating_system: str
21+
22+
# imran = Person("Imran", 22, "Ubuntu") # We can call this constructor - @dataclass generated it for us.
23+
# print(imran) # Prints Person(name='Imran', age=22, preferred_operating_system='Ubuntu')
24+
25+
# imran2 = Person("Imran", 22, "Ubuntu")
26+
# print(imran == imran2) # Prints True
27+
28+
29+
# ------------------------
30+
# Exercise 1
31+
# ------------------------
32+
# Q.Write a Person class using @datatype which uses a datetime.date for date of birth, rather than an int for age.
33+
# Re-add the is_adult method to it.
34+
35+
@dataclass
36+
class Person:
37+
name: str
38+
date_of_birth: date
39+
preferred_operating_system: str
40+
41+
def is_adult(self) -> bool:
42+
today = date.today()
43+
age = today.year - self.date_of_birth.year - ((today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day))
44+
return age >= 18
45+
46+
imran = Person("Imran", date(2002, 1, 12), "Ubuntu")
47+
print(imran.is_adult())

0 commit comments

Comments
 (0)