Search code examples
pythonclassmagic-methods

Why is the same Magic method I used in the following code generating different output than what is expected


class Time:
    def __init__(self, hour=0, minute=0, second=0):
        self.hour = hour
        self.minute = minute
        self.second = second

    def __str__(self):
        return "{}:{:02d}:{:02d}".format(self.hour, self.minute, self.second)

    def __add__(self, other_time):

        new_time = Time()
        if (self.second + other_time.second) >= 60:
            self.minute += 1
            new_time.second = (self.second + other_time.second) - 60
        else:
            new_time.second = self.second + other_time.second

        if (self.minute + other_time.minute) >= 60:
            self.hour += 1
            new_time.minute = (self.minute + other_time.minute) - 60
        else:
            new_time.minute = self.minute + other_time.minute

        if (self.hour + other_time.hour) > 24:
            new_time.hour = (self.hour + other_time.hour) - 24
        else:
            new_time.hour = self.hour + other_time.hour

        return new_time

    def __sub__(self, other_time):

        new_time = Time()
        if (self.second + other_time.second) >= 60:
            self.minute += 1
            new_time.second = (self.second + other_time.second) - 60
        else:
            new_time.second = self.second + other_time.second

        if (self.minute + other_time.minute) >= 60:
            self.hour += 1
            new_time.minute = (self.minute + other_time.minute) - 60
        else:
            new_time.minute = self.minute + other_time.minute

        if (self.hour + other_time.hour) > 24:
            new_time.hour = (self.hour + other_time.hour) - 24
        else:
            new_time.hour = self.hour + other_time.hour

        return new_time


def main():
    time1 = Time(1, 20, 10)

    print(time1)

    time2 = Time(24, 41, 30)

    print(time1 + time2)
    print(time1 - time2)


main()

In the class Time, I have defined methods add and sub with the same function(basically they are the same methods with a different call). when I run print(time1 + time2), print(time1 -time2) I expect to get the same output. But Instead, I end up getting the following output.

Output: 
1:20:10
2:01:40
3:01:40
expected Output:
1:20:10
2:01:40
2:01:40

I would be glad if someone can point out a way to interpret the above code with respect to the output it generates, or explain what is actually happening when I run the above code that is leading to the output generated.


Solution

  • The lines self.minute += 1 and self.hour += 1 mean that your __add__ and __sub__ both modify the left-hand argument to +/-. Thus, after evaluating time1 + time2, the value of time1 will be different, so you'll get a different answer when you then evaluate time1 - time2.