Saturday 5 December 2015

Python: __init__ method

‘__init__’ is a special function called automatically, whenever you are created an object (It is same like constructor in C++, Java).


Employee.py
class Employee:
 """ Blue print for all employees """
 noOfEmployees=0  # Class level variable
  
 def __init__(self, id, firstName, lastName):
  print("Inside Employee constructor")
  self.id = id
  self.firstName = firstName
  self.lastName = lastName
  Employee.noOfEmployees = Employee.noOfEmployees + 1
  
 def displayEmployee(self):
  print(self.id, self.firstName, self.lastName)
  
emp1 = Employee(1, "Hari Krishna", "Gurram")
print("Total Employees", Employee.noOfEmployees)

emp1.displayEmployee()

$ python Employee.py 
Inside Employee constructor
('Total Employees', 1)
(1, 'Hari Krishna', 'Gurram')

Observe the output, the message ‘Inside Employee constructor
‘ is printed first, even though program don’t call the method __init__ explicitly. It is because, whenever you create an object, python calls its __init__ method internally.


Previous                                                 Next                                                 Home

No comments:

Post a Comment