Python __init__ Method

  • Python

__init__() method is one of the special methods in Python. While we need to call other functions, init is always executed whenever the function is instantiated. This function can be used to assign values or maybe for other operations.

class Example:
  def __init__(self):
    print("Inside init")

  def test(self):
    print("Inside Test")

ex1 = Example()
ex1.test()
ex2 = Example()

Output :

Inside init
Inside Test
Inside init

In the above example, we instantiated the class two times and just as we expected, Inside Init go printed twice.

We also can pass some arguments to the objects. To accept the values, we need to also define them inside the function as well.

class Car:
  def __init__(self, type, color):
    self.type = type
    self.color = color

  def drive(self):
    print("Car type is", self.type, "and color is", self.color)

c1 = Car("Hatchback", "Black")

c1.drive()

Output :

Car type is Hatchback and color is Black

In the above example, we pass two arguments to the function, type, and color. We defined them inside the __init__() function as self.type and self.color. Now you must be thinking why did we define as the same name. You can give it any name of your choice like self.t and self.c respectively and will work fine. We are passing self to fetch the values.

Similarly, you can create any number of objects.

c2 = Car("Sedan", "Gold")

c2.drive()

Output :

Car type is Sedan and color is Gold