×

Python Constructor

Introduction

A constructor is defined as the special kind of function or method that is used for instance variables initialization during the creation of an object of a class.

The constructor's task is to assign values(initialize) to the instance members of the class when a class object is created. 

Creating a constructor:

The __init__ method or function is used for creating a constructor of the class and it is also used when an object is created.

As a first argument, it takes the self-keyword which allows accessing the methods and attributes of the class. Initializing the attributes of a class is the most common use of constructor in Python.

Any number of arguments can be passed at the time of creating an object of a class, once the __init__() function is defined. Each class is required to have a constructor, still if it just relies on the default constructor.

Syntax:

def __init__(self):

    # body

Example:

class DummyClass:

    # constructor

    def __init__(self):

        # initializing instance variable

        self.num=200

    # a method

    def read_number(self):

        print(self.num)

# creating object of the class

obj = DummyClass()

# using obj to call the instance method

obj.read_number()

Output:

200

Explanation: In the above example, we have defined how to create a constructor in Python.

Constructors are divided into two types:

  1. Default constructer.
  2. Parametrized constructer.

1. Non-parameterized constructor:

The non-parameterized constructor can be defined as a simple constructor or default constructor.

  • It doesn’t accept any arguments. 
  • This constructor has no parameter exist so, it is called non parametrized constructor or default constructor. 
  • Its definition has only one argument and it works as a reference to the instance being constructed. 
  • It takes only self-reference.
  • When each class object requires to be initialized with the same values, this constructor is very useful at that time.

Example 1:

class JavaTpoint:

    # default constructor

    def __init__(self):

        self.Java = "JavaTpoint"

    # a method for printing data members

    def print_Java(self):

        print(self.Java)

# creating object of the class

obj = JavaTpoint()

# calling the instance method using the object obj

obj.print_Java()

Output:

JavaTpoint

Example 2:

class Person:

#Constructor - non parameterized

def __init__(self):

print("This constructor is non parametrized")

def show(self,name):

print("Hello",name)

person = Person()

person.show("EDDY")

Output:

This constructor is non parametrized

Hello EDDY

2. Parameterized Constructor:

constructor which contains parameters is referred to as a parameterized constructor.

  • The parameterized constructor uses its first argument as a reference to the instance being created called as self and the Programmer provides the rest of the arguments. 
  • The parameterized constructor has many parameters onward with the self. 
  • Parameterized Constructors are the constructor with arguments. 
  • A parameterized constructor can have several arguments.

Example 1:

class Person:

#parameterized constructer

def __init__(self, name):

print("This constructor is parametrized")

self.name = name

def show(self):

print("Hello",self.name)

person = Person("EDDY")

person.show()

Output:

This constructor is parametrized

Hello EDDY

Example 2:

Class Substraction:

    first = 0

    second = 0

    answer = 0

    # parameterized constructor

    def __init__(self, f, s):

        self.first = f

        self.second = s

    def display(self):

        print("First number = " + str(self.first))

        print("Second number = " + str(self.second))

        print("Substraction of number = " + str(self.answer))

    def calculate(self):

        self.answer = self.first - self.second

# creating object of the class

# this will invoke parameterized constructor

obj = Substraction(5000, 3000)

# perform substraction

obj.calculate()

# display result

obj.display()

Output:

First number = 5000

Second number = 3000

Substraction of numbers = 2000

Multiple constructors in a single class

Python does not provide constructor overloading. let's see what happens when we provide it, two constructors.

Example:

class Demo:

def __init__(self):

print("First constructor")

def __init__(self):

print("Second constructor")

    d= Demo()

Output:

Second constructor

Explanation: In the above code, the second constructor is called by the object d whether both have the same specification. The first function is not accessible by the object d. 

Generally, if the class has more than one constructor, then always the last constructor is called by the object of the class. 

When the constructor is not declared

When the constructor is not defined Python provides a default constructor and it instantiates the object.

Example:

class demo:

def show(self):

print("This is a default constructor :)")

>>> d=demo()

>>> d.show()

Output:

This is a default constructor 

Built-in class functions in Python

Here, Various built-in functions in the class exist in Python. Following are the built-in class functions in Python.

  1. getattr(obj,name,default): This built-in function provides access to the attribute of the object.
  2. delattr(obj, name): This function is used to delete a particular class attribute.
  3. setattr(obj, name,value): This function is used, when there is a need to set a specific value to a specific attribute of an object.
  4. hasattr(obj, name): This function returns true if a particular object carries some specific attribute.

Example:

class Employee:

def __init__(self,name,id,age):

self.name = name;

self.id = id;

self.age = age

#creates the object of the class Employee

emp = Employee("EDDY",121,33)

#prints the attribute name of the object s

print(getattr(emp,'name'))

# reset the value of attribute age to 34

setattr(emp,"age",34)

# prints the modified value of age

print(getattr(emp,'age'))

# prints true if the Employee contains the attribute with name id

print(hasattr(emp,'id'))

# deletes the attribute age

delattr(emp,'age')

# this will give an error since the attribute age has been deleted

print(emp.age)

Output:

EDDY

34

True

AttributeError: 'Employee' object has no attribute 'age'

Built-in class attributes in Python

Python also contains built-in class attributes along with built-in class functions. Below are some built-in class attributes in Python.

  1. __dict__: This attributes returns the dictionary that contains some information concerning the class namespace.  
  2. __name__: This attribute is used to returns the current class name.
  3. __doc__: This attribute carries a string, which has the current class documentation.
  4. __module__: We can access the module in which the class is defined.
  5. __bases__: This attribute contains a tuple in which all base classes are included.

Example:

class Employee:    

    def __init__(self,name,id,age):   

        self.name = name;   

        self.id = id;   

        self.age = age   

    def display_details(self):   

        print("Name:%s, ID:%d, age:%d"%(self.name,self.id))   

emp = Employee("EDDY",121,33)   

print(s.__doc__)   

print(s.__dict__)   

print(s.__module__) 

Output:

None

{'name': 'EDDY', 'id': 121, 'age': 33}

__main__

Conclusion

In this article, we have discussed constructors and types of constructors in Python such as parameterized and non-parameterized constructors. Also, We have seen different methods inside the constructors.


Related Topics

Base Case in Recursive function python

In this article, we will learn about Python's base case in a recursive function. Before learning this, let’s first understand what recursion is in Python and the use of recursion in...

6 minutes read.

Python's Qstandarditemmodel

Python More interactive and user-friendly than any other programming language is Python. Many libraries are used by the python programming language to speed up procedures. Python can be used to develop...

3 minutes read.

Python String rstrip() method

Python String rstrip() method The string.rstrip() method in Python returns a copy of the string with trailing characters removed. Syntax string.rstrip([chars]) Parameter chars:  This argument represents a string specifying the set of characters to be...

1 minute read.

An Introduction to Mocking in Python

Python Mocking is a testing library. It enables you to substitute portions of your system under test with fake(mock) objects and make assertions about how they were utilized.  The test is...

3 minutes read.

How to Install Scikit-Learn

Sklearn or Scikit-learn is a python library used for machine learning. It contains many features like classification, regression, clustering, and Dimensionality reduction algorithms. Sklearn is used to build machine learning...

3 minutes read.

Python OOPs: Class, Object, Inheritance and Constructor

Basic Object-Oriented Programming (OOP) Concepts in Python Python is similar to most general-purpose programming languages with an Object-Oriented environment system since its existence. Being an Object-Oriented Programming language, Python provides ease...

9 minutes read.

Python Pass Statement

The pass statement is a null statement. The difference between pass and comment is that comment is ignored by the interpreter, whereas pass is not. The pass statement is typically used...

3 minutes read.

Python Graph

Python Graph: In Computer Science and Mathematics, a Graph is a pictorial representation of a group of objects or elements where some elements are connected using the links. A graph...

5 minutes read.

How to reverse a string in python

How to reverse a string in python A Brief About Strings- The String is a data type in Python that has a sequence of characters. This series of characters are represented in...

4 minutes read.

Python Marshmallow

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Python Argmin

Introduction The argmin function is defined as numpy.argmin(). This function returns the index of the minimum value or element from a Numpy array in a specific axis. An array is taken...

3 minutes read.

Static Variables in Python

What is a Static Variable? The variable that remains with a constant value throughout the program or throughout the class is known as a " Static Variable ". Static variables are...

3 minutes read.

Program of Cumulative Sum in Python

Introduction This tutorial, explains what is meant by lists, the cumulative total, several approaches to calculating the cumulative sum of digits in a list, etc. Learn the straightforward Python codes for...

5 minutes read.

Speech Recognition in Python

What is Speech Recognition? Speech Recognition is a term defined for automatic recognition of human speech. Speech recognition is the most significant activity in the domain of the interaction between the...

8 minutes read.

Python Read CSV file

The CSV stands for “comma-separated value,” which is defined as a simple file format that is used to store data into a tabular form such as a database or spreadsheet. It is...

7 minutes read.

Is Python Case Sensitive

Case sensitivity is the mode of dealing with the written alphabet. The cases of the alphabet are examined and based on these words are being treated. The uppercase and lowercase...

3 minutes read.

Tensorflow Angular in Python

TensorFlow is an open-source, Python-compatible toolkit for numerical computation that accelerates and simplifies the creation of neural networks and machine learning algorithms. They make the interesting notion that models can be...

6 minutes read.

Checking whether a String Contains a Set of Characters in python

In this tutorial, we will learn how to examine or check whether a string contains any set of characters or a substring and if it contains, we will learn how...

6 minutes read.

Python Trigonometric Functions

Before jumping right into the functions and how to use them we need to know what do trigonometric functions mean and how many functions does python has. What are Trigonometric functions? Trigonometric...

3 minutes read.

Confusion Matrix Visualization Python

The confusion matrix is a two-dimensional array that compares the anticipated and actual category labels. These are the True Positive, True Negative, False Positive, and False Negative classification categories for...

4 minutes read.