Building a BetterDate Class
You are developing a time series package and want to define your own class for working with dates, BetterDate
.
The attributes of the class will be year
, month
, and day
. You want to have a constructor that creates BetterDate
objects given the values for year, month, and day, but you also want to be able to create BetterDate
objects from strings, such as 2021-04-30
.
This exercise is part of the course
Introduction to Object-Oriented Programming in Python
Exercise instructions
- Define the class method called
from_str()
, providing the special required argument and another calleddatestr
. - Split
datestr
by hyphens"-"
and store the result as theparts
variable. - Return
year
,month
, andday
, in that order, using the keyword that will also call__init__()
. - Create the
xmas
variable using the class'.from_str()
method, proving the string"2024-12-25"
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
class BetterDate:
def __init__(self, year, month, day):
self.year, self.month, self.day = year, month, day
# Define a class method from_str
____
____
# Split the string at "-"
parts = datestr.____("____")
year, month, day = int(parts[0]), int(parts[1]), int(parts[2])
# Return the class instance
____ ____(____, ____, ____)
# Create the xmas object
xmas = ____.____("____")
print(xmas.year)
print(xmas.month)
print(xmas.day)