-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpractice02Upgraded.py
More file actions
41 lines (29 loc) · 1.18 KB
/
practice02Upgraded.py
File metadata and controls
41 lines (29 loc) · 1.18 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
41
"""
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.
"""
from datetime import date
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):
self.name = name
self.country = country
self.dob = dob # dob in format 'YYYY-MM-DD'
def calculate_age(self):
today = date.today()
has_not_had_birthday = (today.month, today.day) < (self.dob.month, self.dob.day)
age = 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))
person2 = Person("John", "USA", CustomDate(1990, 7, 5))
print(person1.calculate_age())
print(person2.calculate_age())
# Without __str__, this would print <__main__.Person object...>
# With __str__, it prints:
print(person1)