Table of Contents
Python class init
Whenever a beginner starts learning the Python programming language, they come across something like
__init__ which usually they don’t fully understand. In this lesson, we will try to understand the use of
__init__ completely with good examples. Let’s get started.
Understanding python class init function
Let’s see a short code snippet and see what we’re trying to understand:
class Student(object): def __init__(self, something): print("Init called.") self.something = something def method(self): return self.something my_object = Student('Jetty')
What does the
__init__ method do? Why is it necessary? Let’s find out.
What does the python init method do?
When a new instance of a python class is created, it is the
__init__ method which is called and proves to be a very good place where we can modify the object after it has been created.
This means that when we create a new instance of the class like:
my_object = Student('Jetty')
In above snippet, when we called Student with ‘Jetty’ (which could be actually anything), it gets passed to the
__init__ function as the argument, Jetty. Let’s try to run this script now:
Is __init__ the constructor?
__init__ is an oop construct.
__init__ is the constructor for a class. Just like mentioned above, the
__init__ method is called as soon as the memory for the object is allocated. Let’s see what we did above in our snippet:
def __init__(self, something): self.something = something
self is important because if you don’t and implement your method like:
def __init__(self, something): _something = something
something parameter would be stored in variables on the stack and would be discarded as soon as the
__init__ method goes out of scope.
How __init__ works with Inheritance?
When we have a class inheriting from a superclass,
__init__ method works the same way. Let us try to demonstrate what happens when we try to initialise a child class:
class User(object): def __init__(self, something): print("User Init called.") self.something = something def method(self): return self.something class Student(User): def __init__(self, something): User.__init__(self, something) print("Student Init called.") self.something = something def method(self): return self.something my_object = Student('Jetty')
In above code, when we initialised the Student object, this will be the output which is created when we ran the above program:
So, before the child class, the parent’s class init was called. You can control this by modifying the order in which the init is called for a parent or a child class. Read more at python inheritance.
To summarise, python
__init__ is what is called as a constructor in other OOPs languages such as C++ and Java. The basic idea behind this is, it a special method which is automatically called when an object of that Class is created.