What is constructor in python

Share Your Love

Constructor in python is a special method within a class that is automatically called when an object of that class is created. The constructor method is used to initialize the attributes or state of the object. It is defined using the __init__() method.

The __init__() method is known as the initializer or constructor because it initializes the object’s attributes by assigning values to them. It is called implicitly when an object is created using the class name followed by parentheses.

Here’s a basic example of a constructor in Python:

class MyClass:
    def __init__(self, attribute1, attribute2):
        self.attribute1 = attribute1
        self.attribute2 = attribute2

# Creating an object of MyClass and passing values to the constructor
obj = MyClass("Hello", 10)

# Accessing the attributes of the object
print(obj.attribute1)   # Output: Hello
print(obj.attribute2)   # Output: 10

In the above example, the __init__() method takes two parameters (attribute1 and attribute2) in addition to the self parameter, which represents the instance of the class. Inside the constructor, the values passed as arguments are assigned to the object’s attributes (self.attribute1 and self.attribute2).

When the object obj is created using the MyClass constructor, the __init__() method is automatically invoked and initializes the object’s attributes with the provided values. Subsequently, the attributes can be accessed and used within the class or from outside the class using the object name followed by the attribute name (obj.attribute1, obj.attribute2).

The constructor allows you to set the initial state of an object by providing values for its attributes during object creation. It is a crucial part of object-oriented programming as it ensures that the object is properly initialized before any operations are performed on it.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 429

Newsletter Updates

Enter your email address below to subscribe to our newsletter