Apply Now Apply Now Apply Now
header_logo
Post thumbnail
ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING

Python Constructor: Types, Syntax, and Real Examples

By Vishalini Devarajan

When you create objects in Python, something occurs during execution to prepare them for use. This is the constructor. A constructor is not some basic concept you only encounter during your introductory course; rather, it is a core aspect of object design.

In Python, the vast majority of developers only learn and recognize the __init__() method as a constructor and nothing more. Unfortunately, modern Python doesn’t work that way; you are expected to know much more about the concept, and failure to do so leads to non-Pythonic code.

In this article, you will move past the basic explanation of Python constructors and fully understand the ins and outs of how it actually works and is used in modern development.

Table of contents


  1. TL;DR
  2. How Python Constructors Actually Work
  3. Role of __init__() in Practice
  4. Types of Constructors in Python
    • Default Constructor
    • Parameterized Constructor
    • Flexible Constructor Using Default Arguments
  5. __new__ vs __init__: The Real Difference
  6. Why Python Does Not Support Multiple Constructors
  7. Modern Trends for Python Constructors
    • Simpler constructors
    • Dataclasses can automate constructors
    • Using type hints for better readability
    • Factory method rather than complex constructor
  8. Practical Example: Real-World Constructor Design
  9. Common Mistakes Developers Make
  10. Best Practices of Constructors
  11. Conclusion
  12. FAQs
    • What is a Python constructor?
    • Is __init__() the constructor in Python?
    • Can Python have multiple constructors?
    • What is the difference between __new__() and __init__()?
    • Why are dataclasses used instead of constructors?
    • When should you override __new__()?

TL;DR

  1. A Python constructor comprises both the __new__() and the __init__() methods.
  2. The __new__() method handles the creation of the object, while the __init__() method handles the initialization of the object.
  3. Python does not allow multiple constructors per class, but using a variety of features, such as default arguments and class methods, similar results can be achieved.
  4. Modern Python programming often uses dataclasses and type hinting to avoid complex constructor implementations.
  5. Well-written constructors make your code legible, maintainable, and scalable.
  6. An in-depth knowledge of constructor functionality gives you an advantage during technical interviews and in real-world programming.

What is a Python Constructor?

In Python, a constructor is an essential part of the object creation process that helps in the initialization of an object of a class. Primarily, two methods are utilized in this process, which include the __new__() and the __init__() methods, both ensuring that an object is completely set up from the moment it’s created.

How Python Constructors Actually Work

Almost all explanations of Python constructors focus only on the __init__() method. However, Python follows a structured process during object creation.

First, the metaclass’s __call__() method is invoked. Then, __new__() creates the object in memory, and finally, __init__() initializes it.

This sequence shows that __init__() alone is not the complete constructor.

If you want to go deeper into Python object-oriented design, explore this ebook. It gives practical insights into constructors, design patterns, and scalable architecture.

Role of __init__() in Practice

The __init__() method is where most developers spend their time. It is responsible for assigning values and preparing the object for use.

class User:

  def __init__(self, username, email):

      self.username = username

      self.email = email

user1 = User(“harini_dev”, “[email protected]”)

This looks simple, but its impact is significant. Every object created using this class will always have a consistent structure.

Key things to remember:

  1. It runs automatically after object creation.
  2. It must return None.
  3. The first parameter refers to the instance, commonly named self.

Types of Constructors in Python

Python does not have strict constructor types like other languages, but for understanding, we categorize them based on usage.

1. Default Constructor

A constructor that initializes objects with predefined values. It ensures every object starts with the same baseline state.

class Config:

  def __init__(self):

      self.mode = “production”

      self.retry = 3

2. Parameterized Constructor

This allows dynamic initialization using user-provided values. It is the most commonly used type in real-world development.

class Product:

  def __init__(self, name, price):

      self.name = name

      self.price = price

MDN

3. Flexible Constructor Using Default Arguments

Instead of multiple constructors, Python uses default arguments to simulate flexibility.

class Order:

  def __init__(self, item, quantity=1):

      self.item = item

      self.quantity = quantity

This approach replaces the need for constructor overloading.

__new__ vs __init__: The Real Difference

__new__() creates and returns a new object.
__init__() initializes the already created object.

In most cases, you don’t need to override __new__(). But when you do, it gives you deep control.

class Singleton:

  _instance = None

  def __new__(cls):

      if cls._instance is None:

          cls._instance = super().__new__(cls)

      return cls._instance

This ensures only one instance of the class exists.

Why Python Does Not Support Multiple Constructors

Unlike Java or C++, Python does not allow multiple __init__() methods. If you define more than one, only the last one is used.

Instead, Python encourages flexible design patterns.

  1. Use default arguments.
  2. Use *args and **kwargs.
  3. Use class methods as alternative constructors.

class Student:

  def __init__(self, name, marks):

      self.name = name

      self.marks = marks

  @classmethod

  def from_string(cls, data):

      name, marks = data.split(“-“)

      return cls(name, int(marks))

This pattern is widely used in scalable systems.

1. Simpler constructors

Currently, modern Python discourages complex logic in the constructor. Instead, constructors are made simple, and logic is extracted to helper methods.
This enhances readability and testability.

2. Dataclasses can automate constructors

Why rewrite boring, repetitive code when Python offers dataclasses?

from dataclasses import dataclass

@dataclass

class Employee:

  name: str

  salary: int

The dataclass automatically generates the __init__() method and saves you from boilerplate code.

3. Using type hints for better readability

Adding type hints to your constructors would make them easier to read and much more professional.

class Account:

  def __init__(self, balance: float) -> None:

      self.balance = balance

IDEs can now make useful suggestions while you are typing and can easily locate bugs.

4. Factory method rather than complex constructor

If object creation becomes complicated, then you should preferably use a class method.
The constructor now has reduced functionality and is also quite flexible.

If you want to understand how class methods act as alternative constructors, this guide on Python class methods explains their practical usage and design benefits. 

Practical Example: Real-World Constructor Design

Let’s build something closer to a real application.

class BankAccount:

  def __init__(self, name, balance=0):

      self.name = name

      self.balance = balance

  def deposit(self, amount):

      self.balance += amount

  def display(self):

      print(f”{self.name} has balance {self.balance}”)

This example shows how constructors ensure every object starts in a valid state.

If you want to explore the concept in more detail, you can also refer to this Python constructor tutorial, which explains how object creation and initialization work together in Python. 

Common Mistakes Developers Make

Every developer is prone to these mistakes.

  1. Overcrowding __init__() with too much logic.
  2. Considering __init__() the complete constructor.
  3. Creating more than one constructor.
  4. Neglecting input validation on object construction.
  5. Forgetting modern alternatives like dataclasses.

Avoiding these mistakes would automatically elevate the quality of your code.

💡 Did You Know?

If __new__() returns an object of a different type, then __init__() may never be called.

This means there is no guarantee that an object’s initializer will run if __new__() deviates from its default behavior.

While this is a lesser-known detail, it becomes critical in advanced Python designs where object creation is customized.

Best Practices of Constructors

  1. Focus the constructor’s job solely on initializing attributes.
  2. Use informative parameter names and provide default values where appropriate.
  3. Always validate input parameters during object construction to maintain the integrity of the object’s state.
  4. Embrace dataclasses for straightforward data containers.
  5. Leverage class methods for alternative ways to create objects (factory methods).

Adhering to these guidelines will undoubtedly make your code more organized and maintainable.

To gain a deeper and more practical understanding of Python and object-oriented programming, consider enrolling in HCL GUVI’s Python Programming Course. It delves into practical coding techniques, project-oriented learning, and real-world application-based concepts that extend beyond a typical beginner course.

Conclusion

Constructors in Python are deceptively simple on the outside but offer surprising depth. If you only understand __init__(), you are missing out on a vital aspect of the concept.

In modern Python programming, you’re expected to design your classes with minimalist constructors and utilize smart alternatives such as dataclasses and factory methods.

As you delve deeper into the underlying mechanics of constructors, you’ll find your code becoming more organized, predictable, and scalable.

FAQs

1. What is a Python constructor?

A Python constructor is a mechanism used during object creation to initialize an object’s attributes using methods like __new__() and __init__().

2. Is __init__() the constructor in Python?

No, __init__() is technically an initializer. The actual object creation happens in __new__().

3. Can Python have multiple constructors?

No, Python does not support multiple constructors. You can simulate them using default arguments or class methods.

4. What is the difference between __new__() and __init__()?

__new__() creates the object, while __init__() initializes it after creation.

5. Why are dataclasses used instead of constructors?

Dataclasses automatically generate constructors, reducing boilerplate code and improving readability.

MDN

6. When should you override __new__()?

You should override __new__() only in advanced cases like implementing singletons or working with immutable objects.

Success Stories

Did you enjoy this article?

Schedule 1:1 free counselling

Similar Articles

Loading...
Get in Touch
Chat on Whatsapp
Request Callback
Share logo Copy link
Table of contents Table of contents
Table of contents Articles
Close button

  1. TL;DR
  2. How Python Constructors Actually Work
  3. Role of __init__() in Practice
  4. Types of Constructors in Python
    • Default Constructor
    • Parameterized Constructor
    • Flexible Constructor Using Default Arguments
  5. __new__ vs __init__: The Real Difference
  6. Why Python Does Not Support Multiple Constructors
  7. Modern Trends for Python Constructors
    • Simpler constructors
    • Dataclasses can automate constructors
    • Using type hints for better readability
    • Factory method rather than complex constructor
  8. Practical Example: Real-World Constructor Design
  9. Common Mistakes Developers Make
  10. Best Practices of Constructors
  11. Conclusion
  12. FAQs
    • What is a Python constructor?
    • Is __init__() the constructor in Python?
    • Can Python have multiple constructors?
    • What is the difference between __new__() and __init__()?
    • Why are dataclasses used instead of constructors?
    • When should you override __new__()?