我需要写一门涉及日期的课程。我应该超载+
运算符允许将天数添加到日期中。解释一下它是如何工作的:ADate
对象表示为 (2016, 4, 15),格式为(年、月、日)。添加整数 10 应该得到 (2016, 4, 25)。这Date
阶级有价值观self.year
, self.month
, self.day
.
我的问题是代码应该以以下形式工作Date + 10
也10 + Date
. Also Date - 1
应该在添加负数的意义上起作用。Date(2016, 4, 25) - 1
回报Date(2016, 4, 24)
.
我的代码以以下形式完美运行Date + 10
但不是以形式10 + D
or D - 1
.
def __add__(self,value):
if type(self) != int and type(self) != Date or (type(value) != int and type(value) != Date):
raise TypeError
if type(self) == Date:
day = self.day
month = self.month
year = self.year
value = value
if type(value) != int:
raise TypeError
days_to_add = value
while days_to_add > 0:
day+=1
if day == Date.days_in(year,month):
month+=1
if month > 12:
day = 0
month = 1
year+=1
day = 0
days_to_add -=1
return(Date(year,month,day))
这些是我得到的错误
TypeError: unsupported operand type(s) for +: 'int' and 'Date'
TypeError: unsupported operand type(s) for -: 'Date' and 'int'