实现多个构造器,可以使用类方法
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)。