Python Constructors: Types, Rules, and Examples

Python Constructors: Types, Rules, and Examples

In Python, a constructor is a special method used to initialize objects when a class is called. A Python constructor helps set default values to variables, open files, connect to databases, or perform other setup actions. Instead of writing the same code each time an object is created, the Python constructor runs automatically, making the process efficient and cleaner. It also ensures every object starts in a proper state. In object-oriented programming, the Python constructor is important for writing organized and reusable code. In this blog, you will understand what constructors are, how they work, and how to use them with examples.

Table of Contents:

What is a Python Constructor?

A Python constructor is a special method named __init__ that runs automatically to initialize a new object after it is created from a class. The constructor in Python assigns default or user-defined values to an object’s attributes during instantiation. Using the Python constructor helps define the initial state of an object, ensuring consistency across all instances. This makes object creation efficient and avoids repetitive setup code, so developers don’t have to rewrite initialization logic every time a new object is created.

Syntax of Python Constructor  

The syntax of a Python constructor involves defining a special method called __init__() inside a class. This method is automatically invoked whenever a new object is created. The first parameter of the constructor is always self, which refers to the instance being initialized. You can also include additional parameters to assign values to object attributes during creation. Here’s a basic structure:

class ClassName:
def __init__(self, param1, param2):
self.param1 = param1
self.param2 = param2
Master Python: Code Smarter, Build Faster Today!
Learn Python from scratch and create powerful applications, scripts, and automations with ease.
quiz-icon

Working of Python Constructor

In Python, the constructor method is called automatically when an object is created, allowing attributes to be initialized or setup tasks to be performed.

Here’s how it works step-by-step:

  1. Class Definition: You define a class and include an __init__() method.
  2. Object Creation: When an object is created, Python invokes the __init__() method.
  3. Initialization: The constructor assigns values to the object’s attributes using the arguments passed during object creation.
  4. Ready to Use: The object is now initialized and ready for use.

Types of Python Constructors

When creating custom objects through classes, Python allows you to define setup code that is executed automatically after an object is created. This is accomplished using a constructor, a special method in Python that initializes objects.

There are two main types of constructors in Python:

1. Default Constructor in Python

A default constructor is used when no parameters are passed during object creation. It takes only the self parameter and is generally used to assign default attributes.

Example:

Python

Output:

Default Constructor in Python - output

Explanation: Here, the class Device implements a default constructor in Python. When the object d1 is created, no arguments are passed, and thus, Python automatically invokes the constructor with no arguments (other than self) and leaves the status to the default value.

2. Parameterized Constructor in Python

A parameterized constructor allows you to pass arguments during object creation to set initial values. These are values that are used to establish the initial state of the object. This type of Python constructor will enable you to be more flexible and in control.

Example:

Python

Output:

Parameterized Constructor in Python - output

Explanation: Here, the Device class has a parameterized constructor. When d2 is created, “Online” is passed to set the status attribute, showing custom initialization.

Get 100% Hike!

Master Most in Demand Skills Now!

Multiple Python Constructors Using Default Arguments

However, you can simulate multiple constructors in Python using default arguments. This allows a single constructor to handle various initialization cases.

Example:

Python

Output:

Multiple Constructors in Python Using Default Arguments - output

Explanation: Here, a single Python constructor handles different combinations of inputs using default arguments.

Python Constructor with Inheritance

Where one class inherits from another, the Python constructor is important in initialising the parent and child classes’ objects. Python allows you to call the parent class’s constructor inside the child class using the super() function.

Example:

Python

Output:

Constructor in Python with Inheritance - output

Explanation: Here, the child class IntellipaatStudentuses super() to call the parent class constructor. This ensures both name and course_enrolled are initialized properly.

Constructor Overriding in Python Using Inheritance

This means the child class overrides the initialization unless the parent constructor is explicitly invoked using super().

Example:

Python

Output:

Constructor Overriding in Python Using Inheritance - output

Explanation: Here, the child class IntellipaatInstructor defines its own constructor, which overrides the constructor of the parent class IntellipaatUser. As a result, only the child class’s constructor is executed when an object is created.

Advanced Use Cases of the Python Constructor

The Python constructor is not just for setting initial values. It can handle powerful tasks like reading files, validating input, injecting dependencies, and enforcing object behavior. Below are advanced examples that demonstrate the flexibility of the Python constructor.

1. Dependency Injection with Python Constructor

In Python, the object constructor can be utilized to inject the dependencies (services or configurations) into an object.

Example:

Python

Output:

Dependency Injection with Constructor in Python - output

Explanation: Here, the Python constructor takes an external object (Logger) as an argument and uses it.

2. Singleton Design Pattern Using Python Constructor

In Python, the __new__() method can be overridden to implement the Singleton pattern, ensuring only one instance of a class is created. The Python constructor (__init__) still runs, but only after the instance is returned by __new__().

Example: 

Python

Output:

Singleton Design Pattern Using Constructor in Python - output

Explanation: Here, the __new__() method ensures only one instance of the class is created (singleton behavior), while the Python constructor (__init__) initializes that instance.

Common Mistakes While Using Python Constructor

These are common mistakes when using Python constructors. They often lead to unexpected behavior if not used correctly in classes or during object handling.

1. Neglecting to apply self to the Python Constructor

New Python users often forget that instance variables must be accessed or set using self inside the Python constructor. Omitting self creates local variables rather than object-specific attributes, causing unexpected results.

Example:

Python

Output:

Neglecting to apply self to the Creator in Python - output

How to Fix: Remember that all instance variables inside the Python Constructor must be assigned using self. This makes them tied to the object as opposed to the method scope.

Corrected Code:

Python

Output:

Neglecting to apply self to the Creator in Python - 2 - output

Explanation: Here, the instance variable self.name is correctly defined inside the Python constructor, enabling it to be accessed outside the class.

2. Forgetting to call super().__init__() in Inheritance

When using inheritance, if you override the Python constructor in a child class but forget to call the parent’s constructor, essential initialization in the base class gets skipped, which can cause errors.

Example:

Python

Output:

The absence of Calling super().__init__() in Inheritance - output

How to Fix: To ensure proper initialization in a child class, always call super().__init__() inside its constructor. This allows the constructor of the base class to run, setting up inherited attributes correctly.

Corrected Code:

Python

Output:

The absence of Calling super().__init__() in Inheritance - 2 - output

Explanation: Here, the parent constructor is correctly invoked using super(), and inheriting properties such as role are called and set.

Best Practices for Using Python Constructor

1. Keep Python constructors simple: Use the constructor strictly for setting up instance variables and performing lightweight setup tasks. Avoid including complex business logic inside __init__() to keep object creation predictable and efficient. Heavy processing should be delegated to separate methods to maintain clarity and separation of concerns.

2. Use Default Values: In Python, in case parameters are optional, meaningful defaults should always be specified in the constructor. This makes it flexible without compromising functionality.

3. Do not forget super(): The term super() is used in Python to call the constructor of the parent. It assists in consistency and does not skip initialization.

4. Validate Inputs Early: Input validation within constructors in Python helps to identify errors early. This ensures that your objects are solid and data integrity is preserved.

Master Python Basics – 100% Free Learning Path!
Explore variables, loops, functions, and more with free Python tutorials designed for beginners.
quiz-icon

Conclusion

Constructors are essential for initializing Python objects in a way that is both efficient and consistent. They make creating objects easier by automating setup tasks, whether using default values, parameterized inputs, or advanced techniques like dependency injection and singletons. A good understanding of constructors, including how they work with inheritance and dynamic attributes, helps in writing clean, maintainable, and scalable code. By following best practices and being aware of common mistakes, you can build Python classes that are reliable and well-organized.

Take your skills to the next level by enrolling in the Python Course today and gaining hands-on experience. Also, prepare for job interviews with Python Interview Questions prepared by industry experts.

Python Constructors: Types, Rules, and Examples – FAQs

Q1. What is a Python constructor?

A constructor is a special method named __init__ that runs automatically when an object is created.

Q2. Why is __init__() used in Python?

It initializes the attributes of an object when a class is instantiated.

Q3. Can a class have multiple constructors in Python?

Python does not support multiple constructors directly, but you can mimic them using default arguments or class methods.

Q4. Is __init__() required in every class?

No, it’s not required. Python provides a default constructor if you don’t define one.

Q5. How can a child class use the parent class constructor?

A child class can use the parent class constructor by calling super().__init__() inside its own constructor, which ensures the parent’s attributes are properly initialized.

About the Author

Senior Consultant Analytics & Data Science, Eli Lilly and Company

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration. 

EPGC Data Science Artificial Intelligence