PYTHON 8. Overload the operator to allow subtracting two Date objects, producing
ID: 3602799 • Letter: P
Question
PYTHON
8. Overload the operator to allow subtracting two Date objects, producing an int object as a result (and not mutating the Date objects was called on). The difference is the number of days from the left Date to the right Date (which can be negative). For example, Date (2016,6,8) -Date (2016,4,15) returns 54 and Date (2016,4,15) -Date (2016,6,8) returns -54. Hint: use the len function defined above. Also, allow subtracting an int from a Date. It should produce the same value as adding its negative value to a Date: for example, Date (2016,4,15) -1 should produce the same result as Date (2016,4,15)+-1 9. Write the_call_method to allow an object from this class to be callable with three int arguments: update the year of the object to be the first argument, and the month of the object to be the second argument, and the day of the object to be the third argument. Return None. If any parameter is not legal (see how the class is initialized), raise an AssertionBrror with an appropriate string describing the problem/values.Explanation / Answer
I will explain you how to do operator overloading in python
class A:
# your code goes here
now you want to overload subtract operator in class A, it will look like
class A:
def __sub__(self, y):
return self.x - y
coming to the problem statement
add these functions to the class Date
def __sub__(self, date2):
date1 = self.__datetime(self.date1)
if isinstance(date2, int): # this is used to check if int is passed
date2 = date1 + timedelta(days=date2) # convert that to date object
date2 = self.__datetime(date2)
value = date1 - date2 . # gives 5 days
return value # here you use value.total_seconds() , where total_seconds will convert the value to seconds(int)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.