Constructors in Python: Definition, Types, and Rules

Constructors in Python: Definition, Types, and Rules

7 mins read15.9K Views Comment
clickHere
Updated on Apr 12, 2023 18:32 IST

Constructor in python is a special method that is called when an object is created. The purpose of a python constructor is to assign values to the data members within the class when an object is initialized. In this article, we will learn what is python constructor, their types, rules to define constructors in python.

2023_01_python-text-on-blueprint.jpg_s1024x1024wisk20cmFsgDZ-uuEtJ-HpeWvDDg55GHrICDujICydWVsKm7Y.jpg

Constructors in Python is a special class method for creating and initializing an object instance at that class. In Python every class has a constructor; it’s not required to define explicitly. The purpose of the constructor is to construct an object and assign a value to the object’s members.

Explore Python Courses

So, without further delay let’s learn more how to use constructors in Python.

Table of Content

What is Python Constructor

In Python, a constructor is a special method that is called when an object is created. The purpose of a python constructor is to assign values to the data members within the class when an object is initialized. The name of the constructor method is always __init__.

Here is an example of a simple class with a constructor:

 
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("John", 30)
print(person.name)
print(person.age)
Copy code

Output:

John

30

In this example, the __init__ method is called when the Person object is created, and it sets the name and age attributes of the object.

The __init__ method is commonly referred to as the “constructor” because it is responsible for constructing the object. It is called automatically when the object is created, and it is used to initialize the object’s attributes.

Convert YouTube Videos to MP3 using Python
Convert YouTube Videos to MP3 using Python
Python is the ultimate tool for all your tech-savvy needs, and its ability to convert YouTube videos to MP3 files is no exception. If you’re looking for a way to...read more
Bubble Sort Algorithm in Python
Bubble Sort Algorithm in Python
In this article, we will briefly discuss what bubble sort algorithms in python is, how to implement it in python, its working, and complexity.
Fibonacci Number
Fibonacci Number
In this article, we will discuss Fibonacci numbers, it’s application and how to generate them using Python, Java and C.

Types of Python Constructor

In Python, there are two types of constructors:

  • Default Constructor: A default constructor is a constructor that takes no arguments. It is used to create an object with default values for its attributes.
  • Parameterized Constructor: A parameterized constructor is a constructor that takes one or more arguments. It is used to create an object with custom values for its attributes.
  • Non-Parameterized Constructor: A non-parameterized constructor is a constructor that does not take any arguments. It is a special method in Python that is called when you create an instance of a class. The non-parameterized constructor is used to initialize the default values for the instance variables of the object.
What is Programming What is Python
What is Data Science What is Machine Learning

Now let’s look into each one of them in detail.

Default Constructors

Default constructors are useful when you want to create an object with a predefined set of attributes, but you don’t want to specify the values of those attributes when the object is created.

Here is an example of a default constructor:

 
class Person:
def __init__(self):
self.name = "John"
self.age = 30
person = Person()
print(person.name)
print(person.age)
Copy code

Output:

John

30

In this example, the __init__ method is the default constructor for the Person class. It is called automatically when the object is created, and it sets the default values for the name and age attributes.

Parameterized Constructors

Parameterized constructors are useful when you want to create an object with custom values for its attributes. They allow you to specify the values of the object’s attributes when the object is created, rather than using default values.

Here is an example of a class with a parameterized constructor:

 
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 25)
print(person.name)
print(person.age)
Copy code

Output:

Alice

25

In this example, the __init__ method is the parameterized constructor for the Person class. It takes two arguments, name and age, and it sets the values of the name and age attributes of the object to the values of these arguments.

Non-Parameterized Constructors

There is not necessarily a need for a non-parameterized constructor in Python. It is up to the programmer to decide whether to include a non-parameterized constructor in a class.

However, a non-parameterized constructor can be useful in the following cases:

  • When you want to initialize the default values for the instance variables of an object.
  • When you want to perform some operations when an object is created, such as opening a file or establishing a connection to a database.
  • When you want to create a “skeleton” object that can be used as a template for creating other objects.

For example, consider the following class:

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

In this case, the non-parameterized constructor is used to initialize the default values for the instance variables arg1 and arg2. If you create an instance of the MyClass class without passing any arguments, the default values will be used.

 
class MyClass:
def __init__(self):
self.arg1 = 10
self.arg2 = 20
obj = MyClass()
print(obj.arg1)
print(obj.arg2)
Copy code

Output:

10

20

Note: If you do not define a non-parameterized constructor in your class, Python will automatically provide one for you. However, it is a good practice to define a constructor for your class, even if it is a non-parameterized constructor so that you have control over the initialization of your objects.

Rules of Python Constructor

Here are some rules for defining constructors in Python:

  • The constructor method must be named __init__. This is a special name that is recognized by Python as the constructor method.
  • The first argument of the constructor method must be self. This is a reference to the object itself, and it is used to access the object’s attributes and methods.
  • The constructor method must be defined inside the class definition. It cannot be defined outside the class.
  • The constructor method is called automatically when an object is created. You don’t need to call it explicitly.
  • You can define both default and parameterized constructors in a class. If you define both, the parameterized constructor will be used when you pass arguments to the object constructor, and the default constructor will be used when you don’t pass any arguments.
Programming Online Courses and Certification Python Online Courses and Certifications
Data Science Online Courses and Certifications Machine Learning Online Courses and Certifications

Multiple Constructors in Single Class

You can have more than one constructor in a single Python class. This is known as “method overloading”. To do this, you will need to use the same method name (in this case, the name of the method will be the same as the name of the class) but define the method with different numbers or types of arguments.

Here is an example of a class with two constructors:

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

The first constructor takes two arguments and sets them as instance variables, while the second constructor takes only one argument and sets it as an instance variable. When you create an instance of the MyClass class, Python will use the appropriate constructor based on the number of arguments that you pass.

For example:

 
class MyClass:
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
def __init__(self, arg1):
self.arg1 = arg1
self.arg2 = None
obj1 = MyClass(10, 20)
obj2 = MyClass(30)
Copy code

In the first case, the first constructor will be called and arg1 will be set to 10 and arg2 will be set to 20. In the second case, the second constructor will be called and arg1 will be set to 30 and arg2 will be set to None.

Note: Python does not have true method overloading like some other programming languages. When you define multiple methods with the same name in a single class, only the last one will be used. However, you can use default values for arguments to achieve a similar effect.

Conclusion:

In this article we have managed to cover the following concepts associated with constructors in python:

  • What are Constructors in Python?
  • Types of Constructors in Python
  • Rules of Python Constructor
  • Multiple Constructors in Single Class

Hope you will like the article.

Top Trending Article

Top Online Python Compiler | How to Check if a Python String is Palindrome | Feature Selection Technique | Conditional Statement in Python | How to Find Armstrong Number in Python | Data Types in Python | How to Find Second Occurrence of Sub-String in Python String | For Loop in Python |Prime Number | Inheritance in Python | Validating Password using Python Regex | Python List |Market Basket Analysis in Python | Python Dictionary | Python While Loop | Python Split Function | Rock Paper Scissor Game in Python | Python String | How to Generate Random Number in Python | Python Program to Check Leap Year | Slicing in Python

Interview Questions

Data Science Interview Questions | Machine Learning Interview Questions | Statistics Interview Question | Coding Interview Questions | SQL Interview Questions | SQL Query Interview Questions | Data Engineering Interview Questions | Data Structure Interview Questions | Database Interview Questions | Data Modeling Interview Questions | Deep Learning Interview Questions |

FAQs

What is a constructor in Python?

In Python, a constructor is a special method called when a class object is created. It is used to initialize the object's attributes or properties.

What is the purpose of the self parameter in a constructor?

The self parameter in a constructor refers to the object being created. It is used to access the object's attributes and methods.

Can a class have multiple constructors in Python?

No, a class can only have one constructor in Python. However, you can use default values for parameters to create the effect of multiple constructors.

Can a constructor return a value in Python?

No, a constructor in Python does not return a value. Its main purpose is to initialize the object's attributes.

Is a constructor inherited by a subclass in Python?

Yes, a subclass in Python inherits the constructor of its superclass. However, you can also define a new constructor in the subclass to override the constructor of the superclass.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio

Comments