开始使用免费开始使用

可选构造器

Python 也允许您使用 @classmethod 装饰器和特殊的第一个参数 cls 来定义类方法。类方法的主要用途,是定义那些返回该类实例、但不与 __init__() 使用同一段代码的构造逻辑。

例如,您正在开发一个时间序列包,想定义一个用于处理日期的自定义类 BetterDate。该类的属性包括 yearmonthday。您希望既能通过传入 year、month、day 的值来创建 BetterDate 对象,也能从类似 2020-04-30 的字符串创建 BetterDate 对象。

以下函数可能对您有用:

  • .split("-") 方法会在 "-" 处切分字符串为数组,例如 "2020-04-30".split("-") 会返回 ["2020", "04", "30"]
  • int() 会将字符串转换为数字,例如 int("2019") 的结果是 2019

本练习是课程的一部分

Python 面向对象编程

查看课程

交互式实操练习

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

class BetterDate:    
    # Constructor
    def __init__(self, year, month, day):
      # Recall that Python allows multiple variable assignments in one line
      self.year, self.month, self.day = year, month, day
    
    # Define a class method from_str
    ____
    def from_str(____, datestr):
        # Split the string at "-" and convert each part to integer
        parts = datestr.split("-")
        year, month, day = int(parts[0]), ____, ____
        # Return the class instance
        ____ ____(____, ____, ____)
        
bd = BetterDate.from_str('2020-04-30')   
print(bd.year)
print(bd.month)
print(bd.day)
编辑并运行代码