What is __init__ in Python

Published by admin on

__init__ in Python :

If you know how to create python class and objects, you must have seen __init__ method before. For the first comers, this looks different than other methods and classes. In this blog post, I will explain to you what is __init__ and when/how to use it with different examples. Go through the tutorial and drop a comment below if you have any queries.


__init__ as a constructor :

Constructors are methods that gets called first when we create one object. If you know any other object oriented programming language like C++, Java, JavaScript, you might be familiar with it. In python, __init__ method is same as like constructors. It gets called first.

So, we can use this method to do all starting tasks like initializing the instance variables, initialize other class objects etc. This method runs as soon as the object is created. For example, let’s consider the below example program :

class Student:
    def __init__(self,name):
        self.name = name
student = Student('Alex')
print('Student name : {}'.format(student.name))

If you run it, it will print the below output :

Student name : Alex

Here, we are creating one instance of the class Student. String ‘Alex’ is passed as the argument to Student class. The ‘__init__’ method is called first once the object is created or it is initialized. ‘self’ is used to represent the current instance. Using it, we are binding one attribute with the argument. The last line is printing the ‘name’ of the object ‘student’.


__init__ in superclass :

We can invoke __init__ in the super class before executing on the child class using super() method. For example :

class Car:
    def __init__(self, color):
        print('__init__ in Car')
        self.color = color

class Audi(Car):
    def __init__(self, name, color):
        print('__init__ in Audi')
        self.name = name

audi = Audi('XX', 'red')

print('name : {}, color : {}'.format(audi.name, audi.color))

Here, Car is the super class of Audi and we are calling this class when the __init()__ of Audi is called. We are using super() keyword to call this classs or super class. It will invoke the __init()__ method of the super class first and then the sub class. Below is output of this program :

__init__ in Car
__init__ in Audi
name : XX, color : red

Python _init_


Similar tutorials :

Categories: python


Leave a Reply

Your email address will not be published. Required fields are marked *