Aan de slagGa gratis aan de slag

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.

Deze oefening maakt deel uit van de cursus

Introduction to Object-Oriented Programming in Python

Cursus bekijken

Oefeninstructies

  • 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".

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

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)
Code bewerken en uitvoeren