-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpractice02.py
More file actions
40 lines (28 loc) · 1.24 KB
/
practice02.py
File metadata and controls
40 lines (28 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
"""
Write a Python program to create a person class. Include attributes like name, country and date of birth.
Implement a method to determine the person's age.
"""
class CustomDate:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
class Person:
def __init__(self, name, country, dob, current_date):
self.name = name
self.country = country
self.dob = dob # dob in format 'YYYY-MM-DD'
self.today = current_date
def calculate_age(self):
has_not_had_birthday = (self.today.month, self.today.day) < (self.dob.month, self.dob.day)
age = self.today.year - self.dob.year - (1 if has_not_had_birthday else 0)
return age
def __str__(self):
return f"Name: {self.name}, Country: {self.country}, DOB: {self.dob.year}-{self.dob.month}-{self.dob.day}, Age: {self.calculate_age()}"
person1 = Person("Mahesh", "India", CustomDate(2003, 3, 11), CustomDate(2026, 1, 25))
person2 = Person("John", "USA", CustomDate(1990, 7, 5), CustomDate(2026, 1, 25))
print(person1.calculate_age())
print(person2.calculate_age())
# Without __str__, this would print <__main__.Person object...>
# With __str__, it prints:
print(person1)