Types of constructors in Python

Share Your Love

While we are discussing types of constructors in Python, there are primarily two types.

Default Constructor:

  • The default constructor is automatically provided by Python if no constructor is explicitly defined in the class.
  • It takes no arguments other than the self parameter.
  • The default constructor initializes the object with default values or sets up any required initial state.
  • If a class does not have a defined constructor, the default constructor is used implicitly.
  • Example:
class MyClass:
    def __init__(self):
        self.attribute = 10

obj = MyClass()
print(obj.attribute)   # Output: 10

Parameterized Constructor:

  • A parameterized constructor is a constructor that takes one or more parameters in addition to the self parameter.
  • It allows you to pass arguments during the creation of an object and initialize the object’s attributes with those values.
  • The parameterized constructor is explicitly defined in the class, specifying the required parameters and their usage.
  • Example:
class MyClass:
    def __init__(self, attribute1, attribute2):
        self.attribute1 = attribute1
        self.attribute2 = attribute2

obj = MyClass("Hello", 10)
print(obj.attribute1)   # Output: Hello
print(obj.attribute2)   # Output: 10

In addition to these types, Python also supports method overloading, which allows you to define multiple constructors within a class. However, unlike some other programming languages, Python does not support method overloading based on the number or types of parameters.

Therefore, you can only have one __init__() the method in a class. If you need different ways to create objects with varying parameters, you can use default parameter values or use class methods as alternative constructors.

Here’s an example using default parameter values to achieve constructor overloading:

class MyClass:
    def __init__(self, attribute1=None, attribute2=None):
        if attribute1 is None:
            self.attribute1 = "Default"
        else:
            self.attribute1 = attribute1

        if attribute2 is None:
            self.attribute2 = 0
        else:
            self.attribute2 = attribute2

obj1 = MyClass()
print(obj1.attribute1)   # Output: Default
print(obj1.attribute2)   # Output: 0

obj2 = MyClass("Hello", 10)
print(obj2.attribute1)   # Output: Hello
print(obj2.attribute2)   # Output: 10

In this example, the __init__() method accepts two parameters with default values. If no values are provided during object creation, the default values are used. Otherwise, the provided values are assigned to the corresponding attributes.

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: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter