簡體   English   中英

在datetime.time中添加+ =支持

[英]Adding += support to datetime.time

Python的datetime.time類缺少的功能+=datetime.timedelta 我試圖通過創建派生類Time來解決此問題。 然后,我使用datetime +=並獲取datetime.time()

但是,我不知道如何然后傳輸父類值。 我嘗試實現一個copy方法,如下所示,但出現錯誤:

AttributeError: attribute 'hour' of 'datetime.time' objects is not writable

我當前的實現:

from datetime import datetime, timedelta, time

class Time(time):
    def copy(self,other):
        self.hour = other.hour
        self.minute = other.minute
        self.second = other.second
        self.microsecond = other.microsecond

    def __add__(self,other):
        if isinstance(other,timedelta):
            dt = toDatetime(self)
            dt += other
            t = Time()
            t.copy(dt.time())
            return t

如何復制父類的值? 另外,是否有更好的方法讓我獲得相當於datetime.time += datetime.time +=支持,而我只是錯了呢?

要創建副本,請將時間組件傳遞給構造函數

t = Time(dt.hour, dt.minute, dt.second, dt.microsecond)

datetime.time()對象是不可變的; 您可以使用它們的time.replace()方法創建一個替換了特定組件的新實例,但是由於無論如何您都在構造一個新的子類實例,因此傳入組件更加容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM