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):
              self.name   = name
              self.age    = age
              
           def PrintRecord(self):
              print self.name, self.age
        
        
        s1 = CEmployee()
        s2 = CEmployee("Kathir", 33)
        s1.PrintRecord()
        s2.PrintRecord()

		#output
        #unassigned -1
        #kathir 33