Understanding Constructors in Python

Understanding Constructors in Python

19 Jul 2024
Beginner
1.43K Views
9 min read

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 2024

Python Career Guide: Is it worth learning in 2024?

Interview Preparation
Top 50+ Python Interview Questions and Answers

FAQs

Q1. Is Python __ init __ a constructor?

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.

Q2. What is constructor in example?

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

Q3. Which is the constructor __ new __ or __ init __ in Python?

__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

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core ProjectOct 19SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
.NET Solution Architect Certification TrainingOct 20SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Microservices Certification TrainingOct 20SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
ASP.NET Core Certification TrainingOct 20SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification TrainingOct 20SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Azure Developer Certification TrainingOct 27SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Microsoft Azure Cloud Architect with AINov 10SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this