Usage of __init__ and Self in Python Classes

In object-oriented programming, class and object play an important role in doing a certain task. __init__ and self-play such roles in Python object-oriented programming. This article will discuss it.

__init__ in Python

__init__ is a method that acts as a constructor in Python classes. When an object is created for a particular class, the init method will be called, and initialize the variables or attributes defined inside it.

self in Python

Self is a keyword used to access variables and functions inside the class. Also, it represents an instance of class.

Code Example

class Employee:
  def __init__(self, name, department,paid):      
      self.name = name
      self.department = department
      self.paid = paid
  
  def get_department(self):
      return self.department
  
  def get_PaidInfo(self):
      return self.paid
 
obj = Employee("Ajay", "Sales", "Paid")
print("Name of the Employee: "+obj.name)
print("Department: "+obj.get_department())
print("Payment Status: "+obj.get_PaidInfo())
 

Output

Name of the Employee: Ajay
Department: Sales
Payment Status: Paid

In the above example, the Employee class has 3 attributes called name, department, and paid. Inside __init__ method, those variables are declared, when creating object it initializes the value to it. So it acts as an int function acts as a constructors here. The self is used to call the variable and method of class.