【文件属性】:
文件名称:在类中定义多个构造器-华为云大数据中台架构分享
文件大小:5.68MB
文件格式:PDF
更新时间:2021-06-11 11:14:01
Python cookbook 中文 参考
8.16 在类中定义多个构造器
问题
你想实现一个类,除了使用 __init__() 方法外,还有其他方式可以初始化它。
解决方案
为了实现多个构造器,你需要使用到类方法。例如:
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
讨论