1. Learn
  2. /
  3. Courses
  4. /
  5. Introduction to Object-Oriented Programming in Python

Connected

Exercise

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.

Instructions

100 XP
  • Define the class method called from_str(), providing the special required argument and another called datestr.
  • Split datestr by hyphens "-" and store the result as the parts variable.
  • Return year, month, and day, 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".