Constructors in Python: Definition, Types, and Rules

Constructors in Python: Definition, Types, and Rules

7 mins read15.9K Views Comment
Vikram
Vikram Singh
Assistant Manager - Content
Updated on Aug 16, 2024 14:50 IST

A constructor in Python is a special method called when an object is created. Its purpose is to assign values to the data members within the class when an object is initialized. In this article, we will learn what a Python constructor is, its types, and the rules for defining constructors in Python.

constructors in python

 

Constructors in Python is a special class method for creating and initializing an object instance at that class. Every Python class has a constructor; it’s not required to be defined 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 about how to use constructors in Python.

Table of Content

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

– / –
40 hours
– / –
5 days
– / –
3 days
3 K
3 weeks
– / –
4 days
– / –
20 hours
– / –
2 months
Free
6 weeks

What is Python Constructor

In Python, a constructor is a special method called when an object is created. Its purpose 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
Bubble Sort Algorithm in Python
Fibonacci Number

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.

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
author-image
Vikram Singh
Assistant Manager - Content

Vikram has a Postgraduate degree in Applied Mathematics, with a keen interest in Data Science and Machine Learning. He has experience of 2+ years in content creation in Mathematics, Statistics, Data Science, and Mac... Read Full Bio