Defining a plurality of class constructor

Speaking class constructor in Python, typically implemented method __init__ class, for instance initialization (__new__ is used to create instances).
But unlike Java Python methods have shown a very heavy load. Therefore, to achieve a number of different constructors, you may need a different approach.
One approach is to use a class method classmethod, as follows:

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

If not practical classmethod, you might think of an alternative, to allow different calling conventions manner __init __ () method. as follows:

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

While this approach may seem to solve the problem, but the program makes the code difficult to understand and maintain. For example, this implementation does not display useful help string (with the parameter name). In addition, the code will create a Date instance is not clear.

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.

Guess you like

Origin www.cnblogs.com/jeffrey-yang/p/12142780.html