×

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

How to Make an App with Python

In this age of mobiles, rapid mobile application development has got a lot of traction. Moreover, app developers are high in demand because of the increase in digitization. Generally, Python is...

4 minutes read.

Python Variable Scope with Local & Non-local Examples

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.

Difference between Perl and Python

Control and presently utilized for a great many undertakings, including framework organization, web improvement, network programming, and GUI improvement, and the sky is the limit from there. About Perl? Perl is a...

4 minutes read.

Python Set update() method

Python Set update() method The set.update() method in Python updates the current set, by adding items from another set. If an element is common in both the sets, only one appearance of this item...

1 minute read.

Python Switch Case

What is a Switch Case Statement? In the programming languages, a switch statement is a logical loop or syntax that tests the variable's value and compares it with multiple cases. Once...

3 minutes read.

Python program to print calendar

Python program to print the calendar This article will explain how to print the calendar of month and year using Python's calendar module. It's a straightforward thing in Python by importing...

1 minute read.

Simple GUI calculator using PyQt5 in Python

GUI: The user is provided with information using manipulable visual widgets that don't require command-line input. These interface components respond to the user's interactions per the pre-programmed script, assisting each user's...

4 minutes read.

Python Control Flow Statements

This article aims to introduce you to what control flow statements are in general and Control Flow Statements in Python programming Language, the Importance of control flow statements and look...

3 minutes read.

Fsolve in Python

Python Programming Language 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...

3 minutes read.

What is Collaborative Filtering in ML, Python

Introduction Contents recommendation is a useful tactic for almost any specific technology looking to increase interest, but it frequently calls for a lot of user data and perhaps laborious content tagging...

3 minutes read.

Programs for Printing Pyramid Patterns in Python

<!-- wp:paragraph --><p>Python supports printing patterns using basic for loops. The number of rows is handled by the first outer loop, while the number of columns is handled by the...

9 minutes read.

Python String isdigit() method

Python String isdigit() method The string.isdigit() method returns a boolean value true if all characters in the string are digits else for any other value it returns false. Syntax string.isdigit() Parameter NA Return This method returns a...

2 minutes read.

Python ord() Function

Python ord() Function The ord() function in Python returns the number representing the Unicode code of a specified character. Syntax ord(c) Parameter c: This parameter represents a string or any character. Return This function returns the number...

1 minute read.

How to run Python code from the command prompt

The Windows operating system's command-line interpreter is CMD or Command Prompt. The "MS-DOS Prompt" is comparable to Command.com, used in DOS and Windows 9x computers. It is similar to Unix...

3 minutes read.

Pltpcolor in Python

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.

Check if a String is Empty in Python

The string is one of the data types of Python. This data type stores all kinds of data but all the characters must be enclosed using double quotes (""). In...

5 minutes read.

any() Keyword in python

“any” keyword in python This page contains all the information about any () Keyword in python, how it is used with lists, tuples, dictionaries, sets, and what its function is? Python...

3 minutes read.

Python for Loop Increment

Introduction In general, loops are employed for sequential traversal. It belongs to the definite iteration category. Definite iterations imply that the number of iterations is explicitly set in advance.  In this article,...

4 minutes read.

How to Create an Array in Python?

How to Create an Array in Python In the previous article, we have discussed how to declare an array in Python. So, let's have a quick revision of that, and then we...

5 minutes read.

How to find square root in python

How to find Square Root of a number In Python Python makes a lot of tasks easier by using different functions, modules, and libraires. There is an inbuilt function in Python...

6 minutes read.