Your assignment is to write the following magic methods for the Date class. Comp
ID: 3791639 • Letter: Y
Question
Your assignment is to write the following magic methods for the Date class. Complete each method!!! (PLEASE)
PYTHON
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:
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:
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:
Your will receive extra credit if you correctly implement the method below. A correctly implemented version is worth .5 points extra credit.
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:
Explanation / Answer
def __eq__(date1,date2):
if(date1==date2):
return True
else:
return False
def __add__(date,d):
return date+datetime.timedelta(days=d)
def __getitem__(date,item):
if(item=="day" or item==0):
return date.day;
elif(item=="month" or item==1):
return date.month;
elif(item=="year" or item==2):
return date.year;
else:
raise Exception('Invalide input')
def __setitem__(date,index,value):
if(index==0):
date.day=value;
elif(index==1):
date.month=value;
elif(index==2):
date.year=value;
else:
raise Exception('Invalide input')
return date
def __radd__(date,d):
date = date+datetime.timedelta(days=d)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.