PHYTON QUESTIONS Your assignment is to write the following magic methods for the
ID: 3791635 • Letter: P
Question
PHYTON QUESTIONS
Your assignment is to write the following magic methods for the Date class.
1. __eq__ returns True if two Date objects have the same month, day, and year.
2. __add__ is passed an int as a parameter, and adds that number of days to the Date. It is nondestructive. For example:
>>> d = Date(1,31,2017)
>>> d + 5 Date(2,5,2017)
>>> d Date(1,31,2017)
3. __getitem__ is passed either an int between 0 and 2, or a str ‘month’, ‘day’, or ‘year’. It returns the appropriate instance variable from the Date object, or raises an exception otherwise. For example:
>>> d = Date(2,1,2017)
>>> d[0] 2
>>> d[2] 2017
>>> d[‘day’] 1
>>> d[4] # should raise an IndexError
4. __setitem__ is passed an index (as described in problem 4) and an integer, and sets the month, day, or year of the Date object to be that integer. If the index is not of the correct type or value, then an exception is raised. For example:
>>> d = Date(2,1,2017)
>>> d[0] = 5
>>> d Date(5,1,2017)
>>> d[‘year’] = 2020
>>> d Date(5,1,2020)
>>> d[‘moth’] = 31 # should raise an IndexError
5. __radd__ is passed an integer, and modifies the Date object to be the specified number of days into the future. It is destructive. For example:
>>> d = Date(2,1,2017)
>>> d += 28
>>> d Date(3,1,2017)
Explanation / Answer
import datetime
class Date:
def __init__(self, mm, dd, yy):
self.dateObj = datetime.date(yy, mm, dd)
def __eq__(self, date2):
if (self.dateObj == date2.dateObj) :
test = 1
else:
test = 0
return bool(test)
def __add__(self, d):
newDate = self.dateObj + datetime.timedelta(days=d)
return (str(newDate.month) + "/" + str(newDate.day) + "/" + str(newDate.year))
def __getitem__(self, item):
if (item==0) or (item=='month'):
return self.dateObj.month
elif (item==1) or (item=='day'):
return self.dateObj.day
elif (item==2) or (item=='year'):
return self.dateObj.year
else:
raise IndexError("Item passed is not valid")
def __setitem__(self, index, value):
try:
if (index==0) or (index=='month'):
self.dateObj = self.dateObj.replace(month=value)
elif (index==1) or (index=='day'):
self.dateObj = self.dateObj.replace(day=value)
elif (index==2) or (index=='year'):
self.dateObj = self.dateObj.replace(year=value)
else:
raise IndexError("Invalid Index")
except ValueError:
raise IndexError("Invalid Value")
def __radd__(self, value):
self.dateObj = self.dateObj + datetime.timedelta(days=value)
return str(self.dateObj.month) + "/" + str(self.dateObj.day) + "/" + str(self.dateObj.year)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.