Saturday 5 December 2015

Python: Overloading __init__ method

If you are familiar with Java, you can overload constructors like below.
public class Employee {
 private int id;
 private String firstName, lastName;

 Employee() {
  id = -1;
  this.firstName = "Nil";
  this.lastName = "Nil";
 }

 Employee(int id, String firstName) {
  this(id, firstName, firstName);
 }

 Employee(int id, String firstName, String lastName) {
  this.id = id;
  this.firstName = firstName;
  this.lastName = lastName;
 }
 
 ....
 ....
}

In case of Python you have to write a single constructor that handles all cases, using either default arguments or type or capability tests.

For example,

Overloading __init__ using None
Employee.py
class Employee:
 """ Blue print for all employees """
 noOfEmployees=0  # Class level variable
  
 def __init__(self, id=None, firstName=None, lastName=None):
  print("Inside Employee constructor")
  if(id is None and firstName is None and lastName is None):
   self.id = -1
   self.firstName = firstName
   self.lastName = lastName
  else:
   if(firstName is None):
    self.firstName = self.lastName = "Nil"
   elif(lastName is None):
    self.firstName = firstName
    self.lastName = firstName
   else:
    self.firstName = firstName
    self.lastName = lastName
   self.id = id
  
 def displayEmployee(self):
  print(self.id, self.firstName, self.lastName)
  
emp1 = Employee(1, "Hari Krishna", "Gurram")
emp2 = Employee(2)
emp3 = Employee(3, "PTR")
emp4 = Employee()

emp1.displayEmployee()
emp2.displayEmployee()
emp3.displayEmployee()
emp4.displayEmployee()

$ python Employee.py 
Inside Employee constructor
Inside Employee constructor
Inside Employee constructor
Inside Employee constructor
(1, 'Hari Krishna', 'Gurram')
(2, 'Nil', 'Nil')
(3, 'PTR', 'PTR')
(-1, None, None)

Overloading __init__ using default arguments
Employee.py
class Employee:
 """ Blue print for all employees """
 noOfEmployees=0  # Class level variable
  
 def __init__(self, id=-1, firstName="Nil", lastName="Nil"):
  self.id = -1
  self.firstName = firstName
  self.lastName = lastName
  
 def displayEmployee(self):
  print(self.id, self.firstName, self.lastName)
  
emp1 = Employee(id=1, firstName="Hari Krishna", lastName="Gurram")
emp2 = Employee(id=2)
emp3 = Employee(id=3, firstName="PTR")
emp4 = Employee()

emp1.displayEmployee()
emp2.displayEmployee()
emp3.displayEmployee()
emp4.displayEmployee()

$ python Employee.py 
(-1, 'Hari Krishna', 'Gurram')
(-1, 'Nil', 'Nil')
(-1, 'PTR', 'Nil')
(-1, 'Nil', 'Nil')




Previous                                                 Next                                                 Home

No comments:

Post a Comment