Constructors in Python

Share Your Love

In this post I am going to describing how constructors in python behaves like in other programming languages e.g. C++, Java etc.

Constructor Definition:

Generally, a constructor is a method which has the same name as the class name and is used to initialize an object.

In python constructors are treated differently, the class name and the method name of the constructor are different and is only used to initialize the object.

Constructor Creation:

A constructor is created in python using the method __init__().This method is called when the class is instantiated and accepts self as the first argument used to access the methods and attributes of the class.

Let us see an example:

class ClassMy:
    def __init__(self, name, age):
        self.name=name
        self.age=age

    def display(self):
        print("Name: ",self.name)
        print("Age: ", self.age)


c=ClassMy("LingarajTechHub",25)
c.display()

In the above program the name and age are passed in the constructor which is initialized in the variables and displayed in the display function. Where c is the object of the class instantiated.

Output:

J8koM1pV M hcDOy113WYbLEDRvdqEoTR H0TbU GIe6iJfEgZx9yDTBEfdHkxDezEat3eOdu ZAg66doSjwMaXbtzK6OZz 1 iynaySW k CoDptMdOAsUAvlKG0C 6od1nLg

This is a very import concept to deal with in python as we dive deep into python the importance of constructor rises.

Here we come to the end of the discussion on constructors in python. Hope we were able to clear all your doubts.

If you like this post and wants to improve or rewrite please WhatsApp us.

Share Your Love
Avatar photo
Soham Malakar

Hello my name is Soham Malakar am currently pursuing BCA

Coding is one of my favorite hobbies.
I love to code and an enthusiast to learn different types of programming languages.
I love to get intoxicated in the world of technology and video games.
A quick learner possessing better results.

Articles: 40

Newsletter Updates

Enter your email address below to subscribe to our newsletter