Constructors In Python

  • Read
  • Discuss

In Python, a constructor is a special method used to initialize the object with specific properties when the class object is created. The constructor is automatically called when an object is created and is used to set the object’s initial properties.

The constructor method is called __init__. It is defined inside the class and is automatically called when an object of that class is created.

Here is an example of a simple class that has a constructor:

class MyClass:
    def __init__(self, value):
        self.value = value

obj = MyClass(10)
print(obj.value)

The output of the above code is 

In the above example, we defined a class called MyClass with a constructor method __init__. This constructor takes a single argument, value, which is then assigned to an instance variable self.value. When we create an object of this class, we pass in the value 10 assigned to the object’s value attribute.

Default values of constructor in Python

The self parameter refer to the current instance of the class. It is used to access the attributes and methods of the class.

You can also define default values for the attributes inside the constructor.

class MyClass:
    def __init__(self, value=0):
        self.value = value

obj = MyClass()
print(obj.value) 

The output of the above code is 

In the above example, we have defined a default value for the attribute value of 0. The default value is used when the object is created without passing any value to the constructor.

super() function in Python

You can also use the super() function to call the parent class’s constructor. This is useful when you’re creating a subclass and want to reuse the functionality of the parent class.

class Parent:
    def __init__(self, value):
        self.value = value

class Child(Parent):
    def __init__(self, value, extra):
        super().__init__(value)
        self.extra = extra

obj = Child(10, 20)
print(obj.value)
print(obj.extra)

The output of the above code is:

In the example above, we have defined a Parent class with a single attribute value and a Child class that inherits from Parent and adds an extra attribute. The constructor of the Child class calls the constructor of the Parent class using the super() function, passing the value of the value attribute, which is then set to the value attribute of the parent class.

In this tutorial, we’ve covered the basics of constructors in Python, including how to define and use constructors, how to pass arguments to constructors, how to set default values for attributes inside a constructor, and how to use the super() function to call the constructor of a parent class. Constructors are an essential part of object-oriented programming.

Leave a Reply

Leave a Reply

Scroll to Top