Skip to content

Commit 405f2c4

Browse files
committed
methods task
1 parent e1f9545 commit 405f2c4

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

sprint-5/methods.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from datetime import date
2+
# Exercise 1:
3+
# Advantages of methods over free functions:
4+
# 1- Methods keep related data and behavior together
5+
6+
# 2- Methods make code easier to read (person.is_adult() is clearer than is_adult(person))
7+
8+
# 3- Methods reduce the number of parameters (because self already contains the data)
9+
10+
# 4- Methods help mypy catch more errors (because they belong to a specific class)
11+
12+
# 5- Methods make the code more object‑oriented and easier to extend
13+
14+
15+
#Exercise 2 — Change Person to use date of birth
16+
17+
class Person:
18+
def __init__(self, name: str, date_of_birth: date, preferred_operating_system: str):
19+
self.name = name
20+
self.date_of_birth = date_of_birth
21+
self.preferred_operating_system = preferred_operating_system
22+
23+
24+
def is_adult(self):
25+
today = date.today()
26+
age = today.year - self.date_of_birth.year
27+
28+
has_had_birthday_this_year = (
29+
(today.month, today.day) >= (self.date_of_birth.month, self.date_of_birth.day)
30+
)
31+
if not has_had_birthday_this_year:
32+
age -= 1
33+
return age >= 18
34+
35+
imran = Person("Imran", date(2000, 1, 1), "Ubuntu")
36+
print(imran.is_adult())

0 commit comments

Comments
 (0)