1+ from datetime import date
2+
3+
4+ # ------------------------
5+ # Exercise 1
6+ # ------------------------
7+ # Q. Advantages of methods over free functions
8+ # A. Encapsulation - Grouping the data (the attributes) and the behaviour (the methods) together
9+ # means that the code is more organised and easier to understand. It also allows you to hide
10+ # the internal details of how the class works to other parts of the program, so changes
11+ # to the class can be made without affecting external code. Plus, it prevents
12+ # accidental changes to the class's data from outside the class.
13+
14+ # Ease of documentation - When you use methods, all the actions (functions) related to a specific
15+ # thing (like a Person or a String) are grouped inside the class for that thing. This makes it
16+ # easier to find and understand what that thing can do because everything is in one place.
17+
18+ # Inheritance and reusability - methods can be inherited and overridden in subclasses, making them
19+ # reusable and offering customization.
20+
21+ # Access to state - Methods can directly access and modify the data (attributes) of an object using
22+ # self, which free functions cannot do as they are not tied to any specific object.
23+
24+ # Polymorphism - Methods support this by allowing you to define methods with the same name in
25+ # different classes, you call the same methods on different objects but each with behaviour,
26+ # that is specific to that class.
27+
28+
29+ # ------------------------
30+ # Exercise 2
31+ # ------------------------
32+ # Change the Person class to take a date of birth (using the standard library’s datetime.date class)
33+ # and store it in a field instead of age. Update the is_adult method to act the same as before.
34+
35+ class Person :
36+ def __init__ (self , name : str , date_of_birth : date , preferred_operating_system : str ):
37+ self .name = name
38+ self .date_of_birth = date_of_birth
39+ self .preferred_operating_system = preferred_operating_system
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