Using internal attributes
In this exercise, you'll return to the BetterDate class of Chapter 2.
You decide to add a method that checks the validity of the date, but you don't want to make it a part of BetterDate's public interface.
The class BetterDate is available in the script pane.
This exercise is part of the course
Object-Oriented Programming in Python
Exercise instructions
- Add a class attribute
_MAX_DAYSstoring the maximal number of days in a month -31. - Add another class attribute storing the maximal number of months in a year -
12. Use the appropriate naming convention to indicate that this is an internal attribute. - Add an
_is_valid()method that returnsTrueif thedayandmonthattributes are less than or equal to the corresponding maximum values, andFalseotherwise. Make sure to refer to the class attributes by their names!
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Add class attributes for max number of days and months
class BetterDate:
____
def __init__(self, year, month, day):
self.year, self.month, self.day = year, month, day
@classmethod
def from_str(cls, datestr):
year, month, day = map(int, datestr.split("-"))
return cls(year, month, day)
# Add _is_valid() checking day and month values
____
bd1 = BetterDate(2020, 4, 30)
print(bd1._is_valid())
bd2 = BetterDate(2020, 6, 45)
print(bd2._is_valid())