Search for Courses, Topics
certificate icon
Certificate

Learn on Scaler Topics and get certified.

static-certificate

init Function in Python

Learn about init Function in Python.

12 Nov 2021-6 mins read

Introduction to __init__ Function in Python

Python is an object-oriented language. This means that everything in python is an object. Let’s first clear some basics about Object Oriented Programming commonly referred to as OOP.

Let’s say you are making a program which stores information about cars. In that, you will create a class of name Car and then create objects of different cars. When creating a class object we pass different things to it, in the case of cars, it will be company model, year of manufacture, etc. So, inside the class, we need a function that can assign all the arguments passed while creating the object to the newly created object. Or you might wanna print something whenever a new car is added in your program.

For this very task, there is a method called __init__(). This method is called automatically whenever a new object of a class is created. This type of function is also known as the constructor function. A constructor function is a function that is called every time a new object of a class is created.

Here is an example of a class Car that will make the functioning of __init__() more clear.

Syntax:

class Car:
    def __init__(self, name):
        self.name = name
        print("I ran first")
 
    def product(self):
        print("I ran second")
        return ("Name: " + self.name)
 
 
C = Car('Audi R8')
print(C.product())

Output:

I ran first
I ran second
Name: Audi R8

What is __init__ doing?

You can see in the output the order of print statements, __init__ is called first.

__init__ is a magic method which is also called Dunder Methods (These are special methods whose invocation happens internally and they start and end with double underscores). Other examples for magic methods are: __add__, __len__, __str__, etc.

Syntax of init Function in Python

class Songs:
    def __init__(self, arguments):
        # function definition

__init__() function is defined just like a regular python function. Self must be the first argument, after that you can pass arguments of your requirements. The logic of the function comes in the function definition part.

Let’s talk more about __init__.

Understanding __init__ in Python

As explained in the above example __init__ is a special python method that runs whenever a new object is created. These types of functions are used to initialize the attributes of that class, E.g. if the class is Person then the attributes will be name, age, etc.

In other Object-Oriented Languages(like C++, Java), these types of functions are called constructors. Constructors are used to initialize the data members of the class when an object is created. Python uses __init__ method as a constructor to initialize the data members when an object is created for the class. Let’s look at some examples which will help in understanding __init__ better

Syntax :

class Trip:
    def __init__(self, to_city, from_city):
        self.to_city = to_city
        self.from_city = from_city
 
    def holiday(self):
     return ("From: " + self.from_city + "\nTo_city: " + self.to_city)
 
T = Trip('India', 'London')
print(T.holiday())

Output:

From : London
To_city: India

In the above example, a class Trip is created and an object ‘T’ is further created to invoke the methods and attributes. As soon as the object is created,__init__ method is initialized with values ‘India’ and ‘London’ which are assigned to “to_city” and “from_city” respectively. The self keyword represents the current instance of the object. So when the holiday() method is run it prints out the values of from_city and to_city which are London and India respectively.

Syntax :

class Insects:
    def __init__(self, legs, wings):
        self.legs = legs
        self.wings = wings
 
    def looks(self):
        return ("No. of Legs: " + self.legs + "\nNo. of Wings " + self.wings)
 
I = Insects('6', '2')
print(I.looks())

Output:

No. of Legs : 6
No. of Wings: 2

In the above example, object ‘I’ is created to invoke the methods of class Insects, and __init__ method initializes with values ‘6’ and ‘2’ which are assigned to legs and wings respectively. When the looks() method is called the value of legs and wings is printed out to the console.

Use of __init__ in Python

As we discussed earlier, __init__ is a special method used in python programming which is executed whenever a new object is created. Every Object Oriented Programming language has this feature and is called a constructor. Constructors are the functions that run first after the creation of objects and they are useful in assigning values to the newly created objects.

Calling init Function in Python

Generally, we do not call the init manually, it is automatically called when a new object is created. init method is only called manually in the case of inheritance. We will talk about using init in inheritance in the next section. If you want you can call the init() directly, here is how you can do it

Syntax :

class Foo:
    def __init__(self, str):
        self.str = str
 
 
obj = Foo('hello')
print(obj.str)
Foo.__init__(obj, 'Python')
print(obj.str)

Output:

hello
Python

In this code, first we set the value of str linked to obj to ‘hello’ and then calling the __init__() directly we set the value of str to ‘Python’. In this way the __init__() method can be called directly.

Inheritance of __init__ Method in python

Inheritance is a very important concept in OOPs (Object-Oriented Programming). Let’s first understand inheritance in general terms and then we will worry about Python. You might have seen some families where all the members have blue eyeballs. Or somewhere all family members have curly hair. This happens because the genetic information from parents is passed on to the children through a natural process which we call inheritance. This same concept is used when writing Object Oriented code. Here the parents are called the base class and the children are called the derived class.

init Function in Python

The derived class can access the properties and methods of their parent class. In other words, the child class inherits all the methods and properties of their parent class and can add more methods and properties which are unique to them(child class) only. Inside a child class __init__() of the parent class can be called to create object and assign values. Here is an example:

Syntax:

class ParentClass:
    def __init__(self):
        print("Parent Class")
 
class Child(ParentClass):
    def __init__(self):
        ParentClass.__init__(self)
        print('Child Class')
 
obj = Child()

Output:

Parent Class
Child Class

Here when the object of Child class is created, __init__() of the Child class is called which first calls the __init__() of the ParentClass. __init__() of the ParentClass prints out ‘Parent Class’ then print inside the Child class is executed.

Conclusion of init Method in Python

This article had a lot of information about init method in python. Here is a quick summary

  • __init__() is a special python method that runs when an object of a class is created.
  • __init__() function is mostly used for assigning values to newly created objects.
  • __init__() is a magic method which means it is called automatically by Python
  • __init__() can also be invoked manually.
  • __init__() also supports inheritance.

Read More:

  1. Class in Python
  2. Object in Python