0

How do I add another input function where if the current day is Monday and we add 4 dates, the day to be returned is Friday? Been clueless for 2-3 hours now, it's frustrating as hell already

 import operator

class DayOfTheWeek:
    days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

    def __init__(self,day_name):
        day_name = day_name.lower().capitalize()
        if day_name not in self.days:
            raise ValueError("Invalid day name.")
        self.day = day_name

    def __repr__(self):
        return self.day

    def _arithmetic_helper(self,other,operation):
        if isinstance(other,int):
            cur_day_index = self.days.index(self.day)
            after_calc = operation(cur_day_index,other)
            target_day_index = after_calc % len(self.days)
            return type(self)(self.days[target_day_index])
        else:
            return NotImplemented

    def __add__(self,other):
        return self._arithmetic_helper(other,operator.add)

    def __sub__(self,other):
        return self._arithmetic_helper(other,operator.sub)

day = DayOfTheWeek(input("What day is it? "))

for i in range(1,5):
    print(f"Day {i} days ago was {day - i}.")
for i in range(1,5):
    print(f"Day {i} days from today will be {day + i}.")
Dandan20
  • 5
  • 2
  • https://stackoverflow.com/a/6871482/14976472 You might find what you are looking for from here or atleast get an idea of how to do it. – Fresco Jan 30 '21 at 17:51

1 Answers1

0

Would this help?

(Within the DayOfTheWeek class)

def add_days(self):
        days = input("Days to add? ")
        try:
            days = int(days)
            return self + days
        except ValueError:
            # Handle the exception
            print('Please enter an integer')

To call it:

day = DayOfTheWeek(input("What day is it? "))
print(day.add_days())

EDIT

Note 1: The function above returns a DayOfTheWeek object, but it does not modify the original object.

Note 2: Thus, it is possible to save the new object:

day = DayOfTheWeek(input("What day is it? "))
new_day = day.add_days()
print(new_day)

Or to overwrite the original:

day = DayOfTheWeek(input("What day is it? "))
day = day.add_days()
print(day)
Andres Silva
  • 874
  • 1
  • 7
  • 26