Python class init

https://all-learning.com/python-scikit-learn-tutorial/
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:

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:

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:

python-init-inheriatnce

Is __init__ the constructor?

Actually yes. __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:

Using self is important because if you don’t and implement your method like:

The 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:

In above code, when we initialised the Student object, this will be the output which is created when we ran the above program:
python-init-inheriatnce
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.

Conclusion

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.

By admin

Leave a Reply