helo,

I learn Classes and methods according to a manual "Think Python: How to Think Like a Computer Scientist"
I am stuck on "Polymorphism" There is a part using built-in function sum.
I don't know what to do... It should be connected to __add__ function, but still the code must be somhow changed. If I use just total=t1+t2+t3 it works.
Here is a link to a web manual:
http://www.greenteapress.com/thinkpython/html/book018.html#toc189

total=sum([t1,t2,t3])

here is a code:

def int_to_time(seconds):
    time = Time()
    minutes, time.second = divmod(seconds, 60)
    time.hour, time.minute = divmod(minutes, 60)
    return time

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

     def __add__(self, other):
        seconds = self.time_to_int() + other.time_to_int()
        return int_to_time(seconds)

     def time_to_int(self):
        minutes = self.hour * 60 + self.minute
        seconds = minutes * 60 + self.second
        print seconds
        return seconds

     def __str__(self):
        return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)

def main():
    t1 = Time(7, 43)
    t2 = Time(7, 41)
    t3 = Time(7, 37)
    total = sum([t1, t2, t3])
    print total

if __name__ == '__main__':
    main()

I really approciate your help guys. Many thanks!

Edited 5 Years Ago by vlady: n/a

You need to set both __add__ and __radd__ and check for other being integer 0, the sum start value. I do not know if this is official way, but it got it to work:

def int_to_time(seconds):
    time = Time()
    minutes, time.second = divmod(seconds, 60)
    time.hour, time.minute = divmod(minutes, 60)
    return time

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

     def __add__(self, other):
        #print self, other
        if not other:
            seconds = self.time_to_int()
        else:
            seconds = self.time_to_int() + other.time_to_int()
        return int_to_time(seconds)

     __radd__ = __add__
     
     def time_to_int(self):
        minutes = self.hour * 60 + self.minute
        seconds = minutes * 60 + self.second
        return seconds

     def __str__(self):
        return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)

     __repr__ = __str__


def main():
    times = Time(7, 43), Time(7, 41), Time(7, 37)
    print times
    print times[0] + times[1] + times[2] 
    total = sum(times)
    print total

if __name__ == '__main__':
    main()

Edited 5 Years Ago by pyTony: n/a

thanks Tony.

I´d like to use this structure : sum([t1,t2,t3])

yours is a bit different.

I feel like this is too complicated for what you want to do. Can you clarify what you want to do and we could suggest a more simple class structure for it.

This question has already been answered. Start a new discussion instead.