Python - 将天数添加到现有日期

Python - Add days to an existing date

显然这是家庭作业,所以我无法导入,但我也不希望被填满答案。只需要一些可能非常简单的帮助,但现在让我难住了太多小时。我必须向 python 中的现有日期添加天数。这是我的代码:

class Date:
    """
    A class for establishing a date.
    """
    min_year = 1800

    def __init__(self, month = 1, day = 1, year = min_year):
        """
        Checks to see if the date is real.
        """
        self.themonth = month
        self.theday = day
        self.theyear = year
    def __repr__(self):
        """
        Returns the date.
        """
        return '%s/%s/%s' % (self.themonth, self.theday, self.theyear)

    def nextday(self):
        """
        Returns the date of the day after given date.
        """
        m = Date(self.themonth, self.theday, self.theyear)
        monthdays = [31, 29 if m.year_is_leap() else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        maxdays = monthdays[self.themonth]

        if self.theday != maxdays:
            return Date(self.themonth, self.theday+1, self.theyear)
        elif self.theday == maxdays and self.themonth == 12:
            return Date(1,1,self.theyear+1)
        elif self.theday == maxdays and self.themonth != 12:
            return Date(self.themonth+1, 1, self.theyear)

    def prevday(self):
        """
        Returns the date of the day before given date.
        """
        m = Date(self.themonth, self.theday, self.theyear)
        monthdays = [31, 29 if m.year_is_leap() else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        if self.theday == 1 and self.themonth == 1 and self.theyear == 1800:
            raise Exception("No previous date available.")
        if self.theday == 1 and self.themonth == 1 and self.theyear != 1800:
            return Date(12, monthdays[11], self.theyear-1)
        elif self.theday == 1 and self.themonth != 1:
            return Date(self.themonth -1, monthdays[self.themonth-1], self.theyear)
        elif self.theday != 1:
            return Date(self.themonth, self.theday - 1, self.theyear)

    def __add__(self, n):
        """
        Returns a new date after n days are added to given date.
        """
        for x in range(1, n+1):
            g = self.nextday()
        return g

但出于某种原因,我的 __add__ 方法不会 运行 nextday() 正确的次数。有什么建议吗?

这是 运行 正确的次数,但是由于 nextday 不会改变 date 对象,您只是一遍又一遍地询问当前日期之后的日期.尝试:

def __add__(1, n):
    """
    Returns a new date after n days are added to given date.
    """
    g = self.nextday()
    for x in range(1, n):
        g = g.nextday()
    return g

使用 g = self.nextday(),您创建了一个临时对象,然后通过重复将自身分配给第二天来递增该对象。范围必须更改为 range(1,n) 以补偿初始日期,尽管我个人将其写为 range(0,n-1).