I am required to write a class involving dates. I am supposed to overload the +
operator to allow days being added to dates. To explain how it works: A Date
object is represented as (2016, 4, 15) in the format (year, month, date). Adding integer 10 to this should yield (2016, 4, 25). The Date
class has values self.year
, self.month
, self.day
.
My problem is that the code is supposed to work in the form Date + 10
as well as 10 + Date
. Also Date - 1
should work in the sense of adding a negative number of days. Date(2016, 4, 25) - 1
returns Date(2016, 4, 24)
.
My code works perfectly in the form of Date + 10
but not in the form 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))
These are the errors I get
TypeError: unsupported operand type(s) for +: 'int' and 'Date'
TypeError: unsupported operand type(s) for -: 'Date' and 'int'
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…