Press "Enter" to skip to content

Python – Multiple Constructors in a Class Example

The below is a Python program example to demonstrate multiple constructors in a class.

Python Multiple Constructors in a Class Example

import time

class Date:
    # Main First constructor
    def __init__(self, n_year, n_month, n_day):
        self.year = n_year
        self.month = n_month
        self.day = n_day

    # Alternate Second constructor
    @classmethod
    def today(cls):
        t = time.localtime()
        return cls(t.tm_year, t.tm_mon, t.tm_mday)

if __name__ == '__main__':
    a = Date(2019, 2, 6)
    b = Date.today()
    print(a.year, a.month, a.day)
    print(b.year, b.month, b.day)

    class NewDate(Date):
        pass

    c = Date.today()
    d = NewDate.today()
    print('Should be Date instance:', Date)
    print('Should be NewDate instance:', NewDate)

Output

2019 2 6
2019 2 7
Should be Date instance: <class '__main__.Date'>
Should be NewDate instance: <class '__main__.NewDate'>

See also: