add values of object properties hours, minutes and seconds to another object of the same class. if new value for seconds or minutes are more than 60 change as one unit of minute or hour in python

Assuming the class looks something like this:

main.py
class Time:
    def __init__(self, hours=0, minutes=0, seconds=0):
        self.hours = hours
        self.minutes = minutes
        self.seconds = seconds
156 chars
6 lines

To add the values of one Time object to another, you could define a method like this:

main.py
class Time:
    def __init__(self, hours=0, minutes=0, seconds=0):
        self.hours = hours
        self.minutes = minutes
        self.seconds = seconds

    def add_time(self, other_time):
        self.seconds += other_time.seconds
        self.minutes += other_time.minutes
        self.hours += other_time.hours

        if self.seconds >= 60:
            self.seconds -= 60
            self.minutes += 1
        if self.minutes >= 60:
            self.minutes -= 60
            self.hours += 1
501 chars
18 lines

Here, the add_time method takes another Time object as an argument and adds its hours, minutes, and seconds values to those of the current object, while also making sure to carry over excess seconds and minutes as needed.

To use this method to add two Time objects together, you could do something like this:

main.py
t1 = Time(1, 30, 45)
t2 = Time(0, 45, 20)
t1.add_time(t2)
print(t1.hours, t1.minutes, t1.seconds)  # prints "2 16 5"
117 chars
5 lines

gistlibby LogSnag