Software & Finance

Python - Alternate to Multiple Constructors


I have given here python program that explains possible alternatives to multiple Constructors with default arguments. In the init function, __init__ along with the function signature, you can specify a default value to be used. This class example would act as a default constructor and parameterized constructor.

This code is tested with Python version 2.6


        class CEmployee:
           age = 0
           name = ""
           def __init__ (self, name="unassigned", age=-1):
       = name
              self.age    = age
           def PrintRecord(self):
              print, self.age
        s1 = CEmployee()
        s2 = CEmployee("Kathir", 33)

        #unassigned -1
        #kathir 33