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()
В классе Time я определил методы добавлять и суб с одной и той же функцией (в основном это одни и те же методы с другим вызовом). когда я запускаю print (time1 + time2), print (time1 -time2), я ожидаю получить тот же результат. Но вместо этого я получаю следующий результат.
Output:
1:20:10
2:01:40
3:01:40
expected Output:
1:20:10
2:01:40
2:01:40
Я был бы рад, если бы кто-нибудь мог указать способ интерпретации приведенного выше кода в отношении генерируемого им вывода или объяснить, что на самом деле происходит, когда я запускаю приведенный выше код, который приводит к сгенерированному выводу.






Строки self.minute += 1 и self.hour += 1 означают, что ваши __add__ и __sub__ оба модифицируют левый аргумент на + / -. Таким образом, после оценки time1 + time2 значение time1 будет другим, поэтому вы получите другой ответ, когда затем оцените time1 - time2.
Я попробовал ваш код и выяснил следующее: после инструкции
Time(time1+time2)
выполняется, значение time1 теперь 2:20:10, поэтому, когда будет выполнен второй метод, часы будут (24 + 2) -24 вместо (24 + 1) -24