繁体   English   中英

为什么我在以下代码中使用的相同的Magic方法会生成与预期不同的输出

[英]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()

在时间类中,我定义了具有相同功能的方法addsub (基本上它们是具有不同调用的相同方法)。 当我运行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 += 1self.hour += 1这行表示__add____sub__都将左侧参数修改为+ / - 因此,在评估后time1 + time2 ,值time1将是不同的,所以你会得到不同的答案,当你再评估time1 - time2

我已经尝试过您的代码,并发现以下内容:

Time(time1+time2)

运行时,time1的值现在是2:20:10,所以在完成第二种方法后,小时数将是(24 + 2)-24而不是(24 + 1)-24

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM