Skip to content

Commit 5e2a021

Browse files
committed
methods
1 parent 28986eb commit 5e2a021

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Methods.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# EXERCISE 1: Think of the advantages of using methods instead of free functions. Write them down in your notebook
2+
# - Methods keep data and behavior together
3+
# - Methods make code easier to read
4+
# - Methods reduce mistakes
5+
# - Easier to extend and maintain
6+
# - Methods support inheritance
7+
# - Better organization
8+
# - Better organization
9+
# - Methods enable polymorphism
10+
11+
12+
13+
# EXERCISE 2: Change the Person class to take a date of birth (using the standard library’s datetime.date class) and store it in a field instead of age.
14+
# Update the is_adult method to act the same as before.
15+
16+
17+
from datetime import date
18+
from dataclasses import dataclass
19+
20+
@dataclass (frozen=True)
21+
class Person:
22+
name: str
23+
date_of_birth: date
24+
preferred_operating_system: str
25+
26+
def is_adult(self) -> bool:
27+
today = date.today()
28+
age = today.year - self.date_of_birth.year
29+
30+
# Adjust if birthday hasn't happened yet this year
31+
if (today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day):
32+
age -= 1
33+
return age >= 18
34+
35+
imran = Person("Jesus", date(1980, 1, 12), "Ubuntu")
36+
print(imran.is_adult())
37+
38+

0 commit comments

Comments
 (0)