class - how to properly overload the __add__ method in python -
i required write class involving dates. supposed overload + operator allow days being added dates. explain how works: date object represented (2016,4,15) in format year,month, date. adding integer 10 should yield (2016,4,25). date class has values self.year,self.month,self.day
my problem code supposed work in form (date+10) (10+date). date - 1. should work in sense of adding negative number of days. date(2016,4,25) - 1 returns date(2016,4,24).
my code works in form of (date+10) not in form (10+d) or (d-1).
def __add__(self,value): if type(self) != int , type(self) != date or (type(value) != int , 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 errors get
typeerror: unsupported operand type(s) +: 'int' , 'date'
typeerror: unsupported operand type(s) -: 'date' , 'int'
__radd__
handles right side addition need implement well.
i seeing flaws in implementation recommend using datetime
module (especially datetime.timedelta class) @ least handle basic date arithmetic correctly:
import datetime class date(object): def __init__(self, year, month, day): self.year = year self.month = month self.day = day def as_date(self): return datetime.date(self.year, self.month, self.day) def __add__(self, other): if isinstance(other, int): date = self.as_date() + datetime.timedelta(days=other) return date(date.year, date.month, date.day) else: raise valueerror("int value required") def __radd__(self, other): return self.__add__(other) def __sub__(self, other): return self.__add__(-other) def __rsub__(self, other): raise runtimeerror("doesn't make sense.") def __repr__(self): return str(self.as_date())
demo:
>>> date = date(2015, 10, 23) >>> print date + 10 # __add__ called 2015-11-02 >>> print 20 + date # __radd__ called 2015-11-12 >>> print date - 25 # __sub__ called 2015-09-28 >>> print 25 - date # __rsub__ called runtimeerror: doesn't make sense
Comments
Post a Comment