在类中定义多个构造函数

说到Python中的类构造函数,一般是实现类的__init__方法,用以实例初始化(__new__用作创建实例)。
但Python不像Java有很显示的方法重载。因此,若要实现多个不同的构造函数,可能需要另辟蹊径。
一个方案是使用类方法classmethod,如下:

import time

class Date:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    @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

如果不实用classmethod,可能想到另一种方案,以允许不同调用约定的方式实现__init __()方法。如下:

class Date:
    def __init__(self, *args):
        if len(args) == 0:
            t = time.localtime()
            args = (t.tm_year, t.tm_mon, t.tm_mday)
        self.year, self.month, self.day = args

尽管这种方式看起来可以解决问题,但是该方案使得代码难以理解和维护。例如,此实现不会显示有用的帮助字符串(带有参数名称)。 另外,创建Date实例的代码将不太清楚。

a = Date(2012, 12, 21)    # Clear. A specific date. 
 b = Date()               #  ??? What does this do?

# Class method version
c = Date.today()          # Clear. Today's date.

猜你喜欢

转载自www.cnblogs.com/jeffrey-yang/p/12142780.html
今日推荐