【问题标题】:Python - Add days to an existing datePython - 将天数添加到现有日期
【发布时间】:2015-04-15 23:15:43
【问题描述】:

显然这是作业,所以我无法导入,但我也不希望得到答案。只需要一些可能很简单的事情的帮助,但现在已经让我难倒了太多小时。我必须在 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() 正确的次数。有什么建议吗?

【问题讨论】:

  • 运行了多少次?

标签: python class methods operator-overloading


【解决方案1】:

它运行了正确的次数,但由于 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)

【讨论】:

  • @TigerhawkT3 好点;我通常仍然像我提到的那样写它,因为它读起来更好。 范围从 0 到 n-1 而不是 范围到 n-1
猜你喜欢
  • 1970-01-01
  • 2011-01-20
  • 2010-10-08
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 2023-03-09
  • 1970-01-01
相关资源
最近更新 更多