Understanding Constructors in Python

Understanding Constructors in Python

19 Jul 2024
Beginner
2.02K Views
9 min read
Learn with an interactive course and practical hands-on labs

Free Data Structures & Algorithms Online Course

Constructors in Python

Constructors may become your best friend if you're planning to learn Object-Oriented Programming because they are in charge of establishing and initializing new objects in a class. Constructors are a part of Python also. So, if you want to become a good Python developer, you should understand Constructors in Python.

In this Python Tutorial, we are going to cover Python Constructors, including what they are, their rules, the types of Constructors in Python, and the advantages of using them. Let's examine each one.

What is a Constructor?

  • A constructor is a unique method in Python that is invoked automatically when a class object is created.
  • By giving values to the data members of the object, constructors are used to initialize its state.
  • The __init__ method in Python is used to specify the constructor method.

How do you Define a Constructor in Python?

In Python, a constructor is defined by including the __init__ method in the class declaration. Here's an easy example of a constructor in Python

Example

class Employee:
    def __init__(emp, name, age):
       emp.name = name
       emp.age = age
employee1 =Employee("Disha", 33)
print(employee1.name)  
print(employee1.age)

Output

Disha
33

Explanation

__init__ method initializes the name and age attributes of the Employee class.

Rules of Python Constructor

  • Method Name: __init__ is the required method name for the constructor.
  • First Argument: The instance that is being constructed, or self, must be the first argument passed to the constructor method.
  • Optional Arguments: The constructor can accept different options for initialization by adding additional arguments after self.
  • Return Value: The constructor initializes the attributes of the object; it does not return any value.

Types of Constructors in Python

There are three main types of constructors in Python:

  1. Default Constructor
  2. Parameterized Constructor
  3. Non-Parameterized Constructor

Let's see one by one:

1. Python Default Constructor

The Default Constructor is a simple constructor that does not accept any arguments other than self.

class Employee:
    def __init__(self):
        self.data = "Shows Default Data only"
employee1 = Employee()
print(employee1.data)

Output

Shows Default Data only

2. Python Parameterized Constructor

Parameterized Constructor can accept additional arguments to initialize the object's attributes with specific values.

class Employee:
    def __init__(self, data):
        self.data = data
employee2 = Employee("Shows Additional(other parameters) Data")
print(employee2.data)

Output

Shows Additional(other parameters) Data

3. Python Non-Parameterized Constructor

The Python non-parameterized constructor is used when you do not want to manipulate the value or the constructor that has only self as an argument.

Consider the following example.

class Student:  
    # Constructor - non parameterized  
    def __init__(self):  
        print("Non-parametrized constructor:")  
    def show(self,name):  
        print("Hello",name)  
student = Student()  
student.show("Minakshi")      

Output

Non-parametrized constructor:
Hello Minakshi

Multiple Constructors in Single Class

class Student:  
    def __init__(self):  
        print(" Constructor1")  
    def __init__(self):  
        print("Contructor2")  
ss = Student()        

Output

Constructor2

Explanation

Although both constructors have an identical setup, the object "ss"in the code above invoked the second one. The "ss" object cannot access the first method. If a class contains more than one constructor, the object of the class will always internally call the latest constructor.

Advantages of Using Constructors in Python

1. Automatic Initialization

  • Python Constructors gives the guarantee that an object is automatically initialized correctly as soon as it is created.

2. Code Reusability

  • You can reuse the initialization code across various class instances by declaring a constructor.

3. Encapsulation

  • Python Constructors aid in the tidying and organization of the code by helping to encapsulate the initialization logic.

4. Consistency

  • They minimize errors and inconsistencies by offering a consistent method of initializing objects.

Common Mistakes to Avoid with Python Constructors

  • Forgetting calling oneself: In the __init__ method, self should always be the first parameter.
  • Inaccurate Initialization: Verify that the Python constructor has correctly initialized all required attributes.
  • Myth about Overloading: Constructor overloading is not supported by Python. To handle various initialization conditions, instead, use *args and **kwargs or default argument values.
  • Circular imports: When defining constructors that generate instances of other classes within the same module, steer clear of circular imports.
  • Resource Management: Use caution while managing resources (such as opening files or network connections) in constructors. Make sure that destructors (the __del__ method) or context managers are used to clean up afterward properly.
Conclusion
In conclusion, Knowledge of the rules and types of constructors, together with their advantages, helps programmers to produce sturdy and easily maintained code. Constructor use becomes a necessary skill for every Python developer who wants to build solid and efficient object-oriented code. However, to simplify development and improve your game, learn the intricacies of Python with Scholarhat and level up as a Python developer.
Similar Articles of Python
The enumerate() Function in Python
Lambda() Function in Python
10 Python Developer Skills You Must Know in 2025

Python Career Guide: Is it worth learning in 2025?

Interview Preparation
Top 50+ Python Interview Questions and Answers

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 by DotNetTricks)

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