Below is the class definition for a Date class. It represents data using integer
ID: 3857948 • Letter: B
Question
Below is the class definition for a Date class. It represents data using integers for the month and day. For example, February 5 has month number 2 and day equal to 5.
class Date:
def __init__ (self, month, day, year):
self.month = month
self.day = day
def advance(self):
self.day += 1
monthLengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if self.day > monthLengths[self.day]:
self.day = 1
self.month += 1
if self.month > 12:
self.month = 1
Note: this data class ignores leap year.
A. The advance method has a single error that does not relate to leap year. Find the error and change the code to remove the error.
B. Implement the str method for the class. It should give a string representation of the date using the month name and date.
Explanation / Answer
The answer is as follows:
class Date:
def __init__ (self, month, day, year):
self.month = month
self.day = day
self.year = year
def advance(self):
self.day += 1
if (self.year % 100 == 0 and self.year % 400 == 0) or self.year % 4 == 0:
monthLengths = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
else:
monthLengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if self.day > monthLengths[self.month-1]:
self.day = 1
self.month += 1
if self.month > 12:
self.month = 1
def str(self):
if self.month == 1:
name = "January"
if self.month == 2:
name = "February"
if self.month == 3:
name = "March"
if self.month == 4:
name = "April"
if self.month == 5:
name = "May"
if self.month == 6:
name = "June"
if self.month == 7:
name = "July"
if self.month == 8:
name = "August"
if self.month == 9:
name = "September"
if self.month == 10:
name = "October"
if self.month == 11:
name = "November"
if self.month == 12:
name = "December"
print(name," ",self.day," ",self.year)
cal = Date(2,22,2003)
cal.str()
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.