• Post author:
  • Post category:Python
  • Reading time:1 mins read

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
    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):

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


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

See also:

Vinish Kapoor

An Oracle Apex Consultant, Oracle ACE, and founder of foxinfotech.in and orclqa.com a question and answer forum for developers.