Constructor in Python - Scaler Topics (original) (raw)

3 mins readLast updated: 11 Feb 2022856 views

Video Tutorial

FREE

Class Constructor thumbnail

This video belongs to

Python Course for Beginners With Certification: Mastering the Essentials

Overview

In Python, a constructor is a special method within a class designated to initialize new class instances. When an object of the class is created, the constructor is automatically invoked, setting up the object's initial state.

What is a Constructor?

A constructor is a unique function that gets called automatically when an object of a class is created. The main purpose of a constructor is to initialize or assign values to the data members of that class.It cannot return any value other than none.

Let's see how to use the constructor.

Syntax of Python Constructor

Within the 'init' method, you can define the object's initial state by assigning values to the object's properties or performing other necessary startup procedures. The self parameter refers to the current class instance to access class attributes and methods.

Rules of Python Constructor

Self is a reference to the current instance of the class. It is created and passed automatically/implicitly to the __init__() when the constructor is called.

Types of Constructors in Python

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

1. Parameterized Constructor in Python


Parameterized Constructor in Python

In Python, a parameterized constructor is a type of constructor that takes additional arguments besides the standard self reference. These arguments are used to initialize the object's attributes or perform other operations when the object is created.

Here's an example to illustrate this concept:

Code:

Output:

Explanation:

2. Non-Parameterized Constructor in Python


Non-Parameterized Constructor in Python

A non-parameterized constructor in Python is a constructor that does not accept any arguments except the mandatory self. This type of constructor is used for initializing class members with default values or performing standard initialization tasks that do not require external inputs.

Here's an example to illustrate a non-parameterized constructor:

Code:

Output:

Explanation:

3. Default Constructor in Python

When a class is defined without an explicit constructor in Python, Python automatically provides a default constructor. This default constructor is a basic, non-parameterized constructor that performs no specific task or initialization beyond the basic object creation.

Here's an example to illustrate the concept of a default constructor:

Example:

Output:

Explanation:

Become a Python champion with our certification course. Start your journey towards excellence today!

Conclusion