Python类中实现多个构造器

本文介绍如何使用Python的类方法来实现多个构造器。通过定义类方法并使用@classmethod装饰器,可以创建替代构造器,如Date类的today方法,该方法根据当前本地时间返回一个Date实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现多个构造器,可以使用类方法

import time

class Date:
    """方法一:使用类方法"""
    # Primary constructor
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    # Alternate constructor
    """方法二"""
    @classmethod
    def today(cls):
        t = time.localtime()
        return cls(t.tm_year, t.tm_mon, t.tm_mday)

a = Date(2012, 12, 21) # Primary
b = Date.today() # Alternate
print(b.year)

类方法的一个主要用途就是定义多个构造器。它接受一个 class 作为第一个参数(cls)。