In: Computer Science
Python: What are the defintions of the three method below for a class Date?
class Date(object):
"Represents a Calendar date"
def __init__(self, day=0, month=0, year=0):
"Initialize"
pass
def __str__(self):
"Return a printable string representing the date: m/d/y"
pass
def before(self, other):
"Is this date before that?"
Please find the Python code for the following:
Code:
class Date(object):
"Represents a Calendar date"
Day=0
Month=0
Year=0
"Initialize"
def __init__(self, day=0, month=0, year=0):
self.Day=day
self.Month=month
self.Year=year
"Function to return a printable string representing the date:
m/d/y"
def __str__(self):
return str(self.Month)+"/"+str(self.Day)+"/"+str(self.Year)
"Function to check - Is this date before that?"
def before(self, other):
#First compare the year, if it is greater than the other, return
true
if self.Year>other.Year:
return True
#Else then return False which indicates- this date is not before
that
elif self.Year<other.Year:
return False
#Both Year's matches, then check for other
else:
#Secondly compare the month and then return True or False
if self.Month>other.Month:
return True
elif self.Month<other.Month:
return False
#If both are equal, then check for the last parameter Day
else:
#return True, if the day is greater than the other day
if self.Day>other.Day:
return True
#Else returns false
else:
return False
#Validating the above class
d1=Date (12,1,2020)
print("m/d/y:",d1)
print(d1.before(Date(13,1,2020))) #It returns False
print(d1.before(Date(11,1,2020))) #It returns True
Please check the
compiled program and its output for your reference:
Output:
(I believe that I made the code simple and understandable. If you still have any query, Feel free to drop me a comment)
Hope this Helps!!!
Please upvote as well, If you got the answer?
If not please comment, I will Help you with that...