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

时间:2015-04-15 23:15:43

标签: python class methods operator-overloading

显然这是作业,所以我不能进口,但我也不希望被勺子喂答案。只需要一些可能非常简单的东西的帮助,但现在已经让我难以忍受了太多时间。我必须在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()适当的次数。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

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