To create a smarter class that knows about leap years,
I began by adding the
length
method to the base class
Date.
Then I overrode this method with a smarter
length
method in the subclass
LeapDate.
"""
This module is date.py
"""
import calendar
class Date(object):
"Class Date thinks there are no leap years."
lengths = [
None,
31, #January
28, #February
31, #March
30, #April
31, #May
30, #June
31, #July
31, #August
30, #September
31, #October
30, #November
31 #December
]
def __init__(self, month, day, year):
self.year = year
self.month = month
self.day = day
def __str__(self):
"Return a string that looks like the contents of myself."
return f"{self.month:02}/{self.day:02}/{self.year:04}"
def length(self, month, year):
return Date.lengths[month]
def nextDay(self):
"Move myself one day into the future."
if self.day < self.length(self.month, self.year):
self.day += 1
else:
self.day = 1 #Go to the first day of the next month.
if self.month < len(Date.lengths) - 1:
self.month += 1
else:
self.month = 1 #Go to the first month of the next year.
self.year += 1
class LeapDate(Date):
"Class LeapDate knows which years are leap years."
def __init__(self, month, day, year):
super().__init__(month, day, year)
def length(self, month, year):
if month == 2 and calendar.isleap(year):
return 29
return super().length(month, year)
if __name__ == "__main__":
import sys
import datetime
d = LeapDate(2, 28, 2020)
d.nextDay()
print(f"The date after 2/28/2020 is {d}.")
sys.exit(0)
import sys import date #the above date.py module d = date.Date(2, 28, 2020) d.nextDay() print(d) ld = date.LeapDate(2, 28, 2020) ld.nextDay() print(ld)
03/01/2020 02/29/2020
cal 9 1752
September 1752
Su Mo Tu We Th Fr Sa
1 2 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30