8.16 在类中定义多个构造器

问题

你想实现一个类,除了使用 init() 方法外,还有其他方式可以初始化它。

解决方案

为了实现多个构造器,你需要使用到类方法。例如:

  1. import time
  2.  
  3. class Date:
  4. """方法一:使用类方法"""
  5. # Primary constructor
  6. def __init__(self, year, month, day):
  7. self.year = year
  8. self.month = month
  9. self.day = day
  10.  
  11. # Alternate constructor
  12. @classmethod
  13. def today(cls):
  14. t = time.localtime()
  15. return cls(t.tm_year, t.tm_mon, t.tm_mday)

直接调用类方法即可,下面是使用示例:

  1. a = Date(2012, 12, 21) # Primary
  2. b = Date.today() # Alternate

讨论

类方法的一个主要用途就是定义多个构造器。它接受一个 class 作为第一个参数(cls)。你应该注意到了这个类被用来创建并返回最终的实例。在继承时也能工作的很好:

  1. class NewDate(Date):
  2. pass
  3.  
  4. c = Date.today() # Creates an instance of Date (cls=Date)
  5. d = NewDate.today() # Creates an instance of NewDate (cls=NewDate)

原文:

http://python3-cookbook.readthedocs.io/zh_CN/latest/c08/p16_define_more_than_one_constructor_in_class.html