Understanding Constructors in Python

Understanding Constructors in Python

05 Feb 2025
Beginner
2.46K Views
27 min read
Learn with an interactive course and practical hands-on labs

Free DSA Online Course with Certification

Constructors in Python

In Python, constructors are a key concept in Object-Oriented Programming. They are special methods that help you set up everything an object needs as soon as it is created. Think of them as a way to give your objects a solid foundation right from the start.

In this Python tutorial, I will show you how constructors work and how you can use them in your code. Do not worry, it is easier than you think! Let us break it down together and get you comfortable with using constructors. Additionally, enrolling in a Python for Data Scientists with AI training will help you deepen your understanding of Python and its applications in data science and AI. Ready? Let us dive in!

Read More: Python Interview Questions and Answers

What Is a Constructor in Python?

A constructor in Python is a special function used to initialize an instance of a class. It is called automatically when an object is created. Unlike Java or C++, Python uses the __init__() method as its constructor instead of sharing the class name.

Constructors are essential in object-oriented programming as they:

  • Set initial values: Assign default values to class attributes when an object is instantiated.
  • Enable core functionality: Define actions or behavior that should occur when the object is created.
  • Ensure consistency: Standardize how objects of a class are initialized.

Creating a Constructor in Python

Now that you know what a constructor is, let's talk about how to create one in Python. A constructor is a special method that sets up objects in a class. The __init__ method is the most common constructor in Python, and you can use it to set up class attributes right after an object is created.

Every class in Python comes with a constructor. Even if you don’t define one, it just uses the default constructor. When you write your own constructor, the __init__ method is where you define how to initialize attributes. It always takes self as the first parameter so you can access the object’s methods and attributes.

What is __init__ in Python?

The __init__ method is the most widely used constructor in Python. You can use it to give initial values to class attributes or to set up anything the object needs. It is called automatically when you create an object.

Syntax


class ClassName:
    def __init__(self, parameter1, parameter2, ...):
        # Constructor code here
  

Example


class Student:
    def __init__(self, name, roll_number):
        self.name = name
        self.roll_number = roll_number

# Creating an object
student1 = Student("Shailesh", 101)
print(f"Name: {student1.name}, Roll Number: {student1.roll_number}")
  

Output


Name: Shailesh, Roll Number: 101
  

What is __new__ in Python?

The __new__ method is another constructor method in Python, but it works differently. It creates a new instance of a class before __init__ is called. You rarely use __new__, but it’s helpful if you’re working with immutable objects like tuples in Python or customizing object creation.

Syntax


class ClassName:
    def __new__(cls, *args, **kwargs):
        # Custom object creation code here
        return super(ClassName, cls).__new__(cls)
  

Example


class Singleton:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(cls)
        return cls._instance

# Creating multiple objects
obj1 = Singleton()
obj2 = Singleton()
print(obj1 is obj2)  # True, both refer to the same instance
  

Output


True
  

Key Differences Between __new__ and __init__

  • __new__: Creates the object. It’s called before __init__.
  • __init__: Initializes the object. It’s called after __new__.
  • You use __new__ to control object creation and __init__ to initialize attributes.

By combining __new__ and __init__, you can fully customize how objects are created and set up in Python.

Rules of Python Constructor

  • Starts with def: Like any other Python function, a constructor begins with the def keyword.
  • Special method __init__(): The constructor uses __init__(), which is enclosed in double underscores.
  • Purpose of __init__: This method is special because it initializes the object when it is created.
  • First argument is self: The first argument must be self, referring to the object itself. It helps you access its attributes and methods.
  • Automatic call: When you create an object, Python automatically calls the __init__() method.
  • Defined inside the class: You must define the constructor within the class, not outside it.
  • Default and parameterized: If no arguments are passed, the default constructor is used. If arguments are passed, the parameterized constructor is used.

Types of Python Constructor

When working with Python, you’ll encounter constructors, special methods that help you initialize objects. There are three main types of constructors in Python: Default Constructor, Parameterized Constructor, and Non-Parameterized Constructor. Let’s explore them one by one with examples.

Default Constructor

A default constructor is perfect when you want to create an object with predefined values. You don’t need to provide any arguments, it handles everything for you. Want to see how it works?

Example


class Person:
    def __init__(self):
        self.name = "John"
        self.age = 30

# Creating an object
person = Person()
print(person.name)
print(person.age)
  

Output


John
30
  

Explanation

The __init__ method acts as the default constructor here. It assigns predefined values for name and age. When you create an object, these values are automatically set.

Parameterized Constructor

A parameterized constructor lets you create objects with custom values. You can pass arguments to it, making your object flexible. Curious how?

Example


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

# Creating an object
person = Person("Alice", 25)
print(person.name)
print(person.age)
  

Output


Alice
25
  

Explanation

Here, the __init__ method is parameterized. It takes name and age as arguments, allowing you to create objects with custom values for these attributes.

Non-Parameterized Constructor

A non-parameterized constructor doesn’t take any arguments. It’s useful when you want to initialize default values or perform operations like opening a file in File Handling in Python. Let’s see it in action!

Example


class MyClass:
    def __init__(self):
        self.arg1 = 10
        self.arg2 = 20

# Creating an object
obj = MyClass()
print(obj.arg1)
print(obj.arg2)
  

Output


10
20
  

Explanation

The __init__ method initializes default values for arg1 and arg2. When you create an object, these values are ready to use.

Which Constructor Should You Use?

Each type of constructor serves a specific purpose. Use a default constructor for predefined attributes, a parameterized constructor for custom values, and a non-parameterized constructor for initializing default values or performing operations. By choosing the right constructor, you can make your Python code more efficient and easier to manage.

Multiple Constructors in a Single Class

Did you know you can have multiple constructors in one Python class? This is called method overloading. You define multiple versions of the __init__ method with different numbers or types of arguments. But how does Python decide which one to use? Let’s break it down.

How to Use Multiple Constructors

When you define multiple constructors, Python will only use the last defined one. To simulate multiple constructors, you can use default arguments or check the type or number of arguments passed. Curious how it works? Here’s an example!

Example


class MyClass:
    def __init__(self, arg1=None, arg2=None):
        self.arg1 = arg1
        self.arg2 = arg2

# Creating objects with different arguments
obj1 = MyClass(10, 20)
obj2 = MyClass(30)

print(f"obj1: arg1={obj1.arg1}, arg2={obj1.arg2}")
print(f"obj2: arg1={obj2.arg1}, arg2={obj2.arg2}")
  

Output


obj1: arg1=10, arg2=20
obj2: arg1=30, arg2=None
  

Explanation

In this example, the __init__ method accepts two arguments, both of which are optional. If you pass both arg1 and arg2, they are assigned to the respective instance variables. If you pass only arg1, arg2 defaults to None.

Why Can't You Have Multiple __init__ Methods?

Python doesn’t support multiple constructors with the same name, as it would override the earlier definitions. Instead, you can handle different cases within a single __init__ method using default arguments or conditional logic. This keeps your code simple and effective.

Tips for Using Multiple Constructors

  • Use default arguments when possible to simplify initialization.
  • Leverage conditional logic for complex constructor behavior.
  • Keep your constructors clean and focused to maintain readability.

By understanding how to use constructors efficiently, you can make your classes versatile and adaptable to different situations!

Multiple Constructors in a Single Python Class

Unlike some programming languages, Python doesn’t support multiple constructors with different parameter lists. But don’t worry,you can achieve the same result by using default arguments and conditional logic within a single __init__ method.

This is known as constructor overloading or method overloading in Python. It lets you create a class that handles various initialization cases, making object creation flexible. How does it work? Let’s find out!

Example


class Rectangle:
    def __init__(self, width=0, height=0):
        if width and height:
            self.width = width
            self.height = height
        elif width:  # Single argument used as a square's side
            self.width = width
            self.height = width
        else:  # No arguments
            self.width = 0
            self.height = 0

    def area(self):
        return self.width * self.height

    def display_info(self):
        print(f"Width: {self.width}, Height: {self.height}, Area: {self.area()}")

# Create instances using different "constructors"
rect1 = Rectangle(10, 20)  # Two arguments
rect2 = Rectangle(10)      # One argument (treated as square)
rect3 = Rectangle()        # No arguments

# Display the rectangles' information
rect1.display_info()  # Width: 10, Height: 20, Area: 200
rect2.display_info()  # Width: 10, Height: 10, Area: 100
rect3.display_info()  # Width: 0, Height: 0, Area: 0
  

Output


Width: 10, Height: 20, Area: 200
Width: 10, Height: 10, Area: 100
Width: 0, Height: 0, Area: 0
  

Explanation

In this example, the __init__ method of the Rectangle class handles three different cases:

  • If both width and height are provided, it initializes a rectangle with those dimensions.
  • If only width is provided, it assumes you want a square and sets both dimensions to the same value.
  • If no arguments are provided, it initializes a rectangle with zero dimensions.
Explore More:
Constructor Overloading in Java
Method Overloading in Java

Key Takeaways

  • Use default arguments in the constructor to handle multiple initialization cases.
  • Employ conditional logic to customize object creation based on the arguments passed.
  • By doing this, you make your class flexible and easier to work with in different situations.

Now you know how to create classes in Python that behave as if they have multiple constructors. Try it yourself and see how versatile your code can be!

Advantages and Disadvantages of Using Constructors in Python

Constructors in Python are crucial for initializing objects and ensuring that each object is created with the proper attributes. They offer various benefits, such as code readability and efficient memory usage, but also come with certain challenges, including overloading complexity and dependency issues. Below is a table summarizing the advantages and disadvantages:

AdvantagesDisadvantages
Improved Readability: Constructors provide structure by clearly stating how values are initialized, enhancing code readability and maintainability.Overloading Complexity: Python doesn’t natively support constructor overloading, which may confuse programmers transitioning from other languages.
Automatic Invocation: Constructors are invoked automatically when objects are created, ensuring proper initialization and reducing errors.Limited Functionality: Python constructors lack features like access modifiers that are available in other languages.
Easy Initialization: Constructors efficiently assign initial values to class attributes, allowing for streamlined object creation.Overhead Complications: Poorly implemented constructors can lead to overhead and slow down program execution.
Flexible Object Creation: Parameterized constructors allow objects to have unique attributes, making programming more dynamic.Error Propagation: Errors in constructors can affect all objects of a class, leading to widespread program issues.
Easy Implementation: Python constructors are simple to define using the __init__ method, making them beginner-friendly.Issues with Multiple Constructors: Python doesn’t support method overloading, so having multiple constructors with different parameters is not possible.
Efficient Memory Usage: Constructors initialize objects when needed, reducing resource redundancy and minimizing memory usage.Dependency Issues: Excessive reliance on constructors can reduce modularity and complicate management in complex projects.
Code Consistency: Using constructors ensures uniform object initialization, preventing inconsistency between objects of the same class.Initialization Challenges: Constructors may lack flexibility when diverse object initialization methods are required.

Common Mistakes to Avoid with Python Constructors

  • Forgetting to Call 'self': In the __init__ method, ensure that self is always the first parameter.
  • Inaccurate Initialization: Always verify that the constructor properly initializes all required attributes.
  • Myth about Overloading: Python does not support constructor overloading. Use *args, **kwargs, or default argument values to handle different initialization conditions.
  • Avoiding Circular Imports: Be cautious when defining constructors that create instances of other classes within the same module. Circular imports should be avoided.
  • Resource Management: Exercise caution when managing resources (e.g., opening files or network connections) within constructors. Ensure proper cleanup using destructors (__del__) or context managers.
Read More: Python Developer Roadmap
Summary

This article explained the importance of constructors in Python and their role in object initialization. You’ve learned how the __init__ method is used to initialize object attributes and how Python constructors can improve code readability and reduce errors. Understanding constructors is essential for writing well-structured and efficient code. Whether you're a beginner or advancing your Python skills, mastering constructors is a key step in enhancing your Python programming abilities. Want to deepen your Python knowledge? Enroll in the Scholarhat Python For Data Science and AICertification Trainingtodayand enhanceyourexpertise in Python programming!

Looking to expand your programming skills for free? Check out these Scholarhat Free Courses:

Test Your Knowledge of Constructors in Python!

Q 1: What is the purpose of the `__init__` method in Python?

  • (a) To define a class
  • (b) To initialize object attributes
  • (c) To destroy objects
  • (d) To call other methods in the class

Q 2: Can you have multiple constructors in Python?

  • (a) Yes, using method overloading
  • (b) No, Python doesn’t support method overloading
  • (c) Yes, by using different names for constructors
  • (d) Yes, using default arguments

Q 3: What happens if you don’t define the `__init__` method in a Python class?

  • (a) An error occurs when creating an object
  • (b) The class will inherit the `__init__` method from its parent class
  • (c) The object cannot be initialized
  • (d) Python automatically creates an `__init__` method

Q 4: Can the `__init__` method in Python return a value?

  • (a) Yes, it can return a value
  • (b) No, it cannot return a value
  • (c) Yes, but only if the value is a boolean
  • (d) Yes, it can return a string

Q 5: What will happen if you call the `__init__` method explicitly in Python?

  • (a) It will create a new object
  • (b) It will initialize the object again
  • (c) It will override the existing object
  • (d) It will raise an error

FAQs

Yes, __init__ is considered a constructor in Python. It is a special method that is automatically called when an instance (object) of a class is created. Its primary purpose is to initialize the attributes of the object.

A constructor in Java is similar to a method that is invoked when an object of the class is created. 

__new__ is responsible for creating and returning a new instance, while __init__ is responsible for initializing the attributes of the newly created object. __new__ is called before __init__ . __new__ happens first, then __init__ . __new__ can return any object, while __init__ must return None 
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this