簡體   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