Python class constructor function

  • by

Python class constructor is used to initialize the instance of the class. Python has __init__() constructor function for the Python classes.

The method __init__( ) executes every object creation of that class. It’s a special method or member function of a class that automatically gets executes on every object creation. It is always called when an object is created.

Syntax of constructor declaration :

def __init__(self):
    # body of the constructor

The def keyword is used to define function.

Types of constructors

  • Default Constructor – is a constructor without any parameters, however, it has a default parameter self.
  • Parameterized Constructor – is a constructor with one or more parameters.

Examples Class Constructor in Python

Simple example code. Constructors also verify that there are enough resources for the object to perform any start-up task.

Creating Default Constructor Python class

This constructor has the same name as the class name.

class Test:
    num = 0

    def __init__(self):
        self.num = 100
        print(f'Object has created!')
        print(self.num)


# creating object
obj = Test()

Output:

Python class constructor function

Creating Parameterized Constructor

The constructor may have any number of parameters. Let’s see an example with single parameters.

class Test:
    i = 10

    def __init__(self, value):
        self.i += value
        print(self.i)


# creating object
obj = Test(10)

Output: 20

Counting the number of objects of a class

Let’s count how many times objects are created for any class.

class Students:
    count = 0

    def __init__(self):
        Students.count += 1


s1 = Students()
s2 = Students()
s3 = Students()
print("The number of students:", Students.count)

Output: The number of students: 3

Do comment if you have any doubts and suggestions on this Python class tutorial.

Note: IDE: PyCharm 2021.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.