How to create a Date object in python? -
i asked, exercise, build class in python, named "date". have build few functions according requirements. first 1 "init" model takes day, month, year, hours, , minutes , returns valid date object(when valid means month, instance, can't 13.) next function raises specific error if data invalid, 13 month. my problem that whenever call "date(23,14,1998).month", returns "13" instead of error. not sure how valid date object created. use help. code:
class date: days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def __init__(self, day, month, year, hours=0, minutes=0): self.day=day self.month=month self.year=year self.hours=hours self.minutes=minutes def validate(self): if type(self.month)==int: if self.month<1: raise valueerror('error: month value must positive') if self.month>12: raise valueerror('error: month value cannot exceed 12') else: raise valueerror('error: month value must integer') if type(self.day)==int: if self.day>days_in_month(self): raise valueerror('error: maximum days in month exceeded') elif self.day<1: raise valueerror('error: day value must positive') else: raise valueerror('error: day value must integer') if type(self.hours)==int: if self.month>23: raise valueerror('error: hours value cannot exceed 23') elif self.month<0: raise valueerror('error: hours value cannot negative') else: raise valueerror('error: hours value must integer') if type(self.minutes)==int: if self.month>59: raise valueerror('error: minutes value cannot exceed 59') elif self.month<0: raise valueerror('error: minutes value cannot negative') else: raise valueerror('error: minutes value must integer') def days_in_month(self): if self.month == 2 , self.is_leap_year(): return 29 return self.days_per_month[self.month-1] def is_leap_year(self): if self.year % 400 == 0: return true elif self.year % 100 == 0: return false elif self.year % 4 == 0: return true else: return false
consider calling self.validate()
in __init__
after assigning variable.
Comments
Post a Comment