开始使用免费开始使用

构建 BetterDate 类

您正在开发一个时间序列包,想要定义一个用于处理日期的自定义类 BetterDate

该类的属性为 yearmonthday。您希望通过一个构造函数,在给定年、月、日的值时创建 BetterDate 对象,同时也希望能从字符串(例如 2021-04-30)创建 BetterDate 对象。

本练习是课程的一部分

Python 面向对象编程入门

查看课程

练习说明

  • 定义名为 from_str() 的类方法,提供必需的特殊参数以及一个名为 datestr 的参数。
  • 使用连字符 "-" 拆分 datestr,并将结果保存为变量 parts
  • 使用会调用 __init__() 的关键字,按顺序返回 yearmonthday
  • 使用类的 .from_str() 方法创建变量 xmas,传入字符串 "2024-12-25"

交互式实操练习

通过完成这段示例代码来试试这个练习。

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)
编辑并运行代码