Sitemap

Python InIt Function Explained

1 min readJul 6, 2023

--

In this tutorial, we’ll learn what Python init function is and how to properly use it. We’ll go through multiple practical Python examples for better understanding.

Introduction: Python init Function

In Python class-object concept, init function is used to automatically initialize the object with some values when its created. Its used inside the class. Its automatically called when the object of that same class is created.

Get Zeeshan Ali’s stories in your inbox

Join Medium for free to get updates from this writer.

Let’s now practically understand how to use init function in Python class.

Syntax of init Function

def __init__(self):
// body of init
  • It starts with def keyword.
  • Two underscores before and after the name.
  • Self works as an instance of object and its necessary. Or else, exception will raised while creating object of this class. Name can be self, a, b etc.
  • We can also specify other parameters to accept some values when the object is created.
  • Colon(:) is necessary after the ending parenthesis.
  • In the next line, we can specify body of this init method. Indentation is required.

Implementing Python init Function (Multiple Examples)

Below examples will explain the implementation and usage of Python init function.

Example 1: Simple Python init Function

class Fun:
def __init__(self):
print('Init runs automatically')
obj=Fun()

Output

Init runs automatically

We can see that init runs automatically when the object of that specific class is created. As a result, the print function inside this init function is executed. Continue reading…

--

--

Zeeshan Ali
Zeeshan Ali

Written by Zeeshan Ali

I am a Python developer and I am here to share what i have learnt so far. Hope my posts will help you in your python development journey. www.letmeflutter.com