Python Tutorial

Introduction Python Features Python Applications System requirements for Python Python Installation Python Basics Python Variables Python Data Types Python IDE Python Keywords Python Operators Python Comments Python Pass Statement

Python Conditional Statements

Python if Statement Python elif Statement Python If-else statement Python Switch Case

Python Loops

Python for loop Python while loop Python Break Statement Python Continue Statement Python Goto Statement

Python Arrays

Python Array Python Matrix

Python Strings

Python Strings Python Regex

Python Built-in Data Structure

Python Lists Python Tuples Python Lists vs Tuples Python Dictionary Python Sets

Python Functions

Python Function Python min() function Python max() function Python User-define Functions Python Built-in Functions Anonymous/Lambda Function in Python

Python File Handling

Python File Handling Python Read CSV Python Write CSV Python Read Excel Python Write Excel Python Read Text File Python Write Text File Read JSON File in Python

Python Exception Handling

Python Exception Handling Python Errors and exceptions Python Assert

Python OOPs Concept

OOPs Concepts in Python Classes & Objects in Python Inheritance in Python Polymorphism in Python Python Encapsulation Python Constructor Static Variables in Python Abstraction in Python

Python Iterators

Iterators in Python Yield Statement In Python

Python Generators

Python Generator

Python Decorators

Python Decorator

Python Functions and Methods

Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods

Python Modules

Python Modules Python Datetime Module Python Calendar Module  

Python MySQL

Python MySQL Python MySQL Update Operation Python MySQL Delete Operation

Python MongoDB

Python MongoDB

Python Data Structure Implementation

Python Stack Python Queue Python Hash Table Python Graph

Python Advance Topics

Speech Recognition in Python Face Recognition in Python Python Rest API Python Command Line Arguments Python JSON Python Virtual Environment Type Casting in Python Collections in python Python Enumerate Python Debugger Python DefaultDict

Misc

Python PPTX Python Pickle Python Seaborn Python Coroutine Python EOL Python Infinity Python math.cos and math.acos function Python Project Ideas Based On Django Reverse a String in Python Reverse a Number in Python Python Word Tokenizer Python Trigonometric Functions Python try catch exception GUI Calculator in Python Implementing geometric shapes into the game in python Installing Packages in Python Python Try Except Python Sending Email Socket Programming in Python Python CGI Programming Python Data Structures Python abstract class Python Compiler Python K-Means Clustering List Comprehension in Python3 NSE Tools In Python Operator Module In Python Palindrome In Python Permutations in Python Pillow Python introduction and setup Python Functionalities of Pillow Module Python Argmin Python whois Python JSON Schema Python lock Return Statement In Python Reverse a sentence In Python tell() function in Python Why learn Python? Write Dictionary to CSV in Python Write a String in Python Binary Search Visualization using Pygame in Python Latest Project Ideas using Python 2022 Closest Pair of Points in Python ComboBox in Python Python vs R Python Ternary Operators Self in Python Python vs Java Python Modulo Python Packages Python Syntax Python Uses Python Logical Operators Python Multiprocessing Python History Difference between Input() and raw_input() functions in Python Conditional Statements in python Confusion Matrix Visualization Python Python Algorithms Python Modules List Difference between Python 2 and Python 3 Is Python Case Sensitive Method Overloading in Python Python Arithmetic Operators Design patterns in python Assignment Operators in Python Is Python Object Oriented Programming language Division in Python Python exit commands Continue And Pass Statements In Python Colors In Python Convert String Into Int In Python Convert String To Binary In Python Convert Uppercase To Lowercase In Python Convert XML To JSON In Python Converting Set To List In Python Covariance In Python CSV Module In Python Decision Tree In Python Difference Between Yield And Return In Python Dynamic Typing In Python Abstract design pattern in python Builder design pattern in python Prototype design pattern in Python Creational design patterns in Python

How to

How to convert integer to float in Python How to reverse a string in Python How to take input in Python How to install Python in Windows How to install Python in Ubuntu How to install PIP in Python How to call a function in Python How to download Python How to comment multiple lines in Python How to create a file in Python How to create a list in Python How to declare array in Python How to clear screen in Python How to convert string to list in Python How to take multiple inputs in Python How to write a program in Python How to compare two strings in Python How to create a dictionary in Python How to create an array in Python How to update Python How to compare two lists in Python How to concatenate two strings in Python How to print pattern in Python How to check data type in python How to slice a list in python How to implement classifiers in Python How To Print Colored Text in Python How to develop a game in python How to print in same line in python How to create a class in python How to find square root in python How to import numy in python How to import pandas in python How to uninstall python How to upgrade PIP in python How to append a string in python How to open a file in python

Sorting

Python Sort List Sort Dictionary in Python Python sort() function Python Bubble Sort

Programs

Factorial Program in Python Prime Number Program in Python Fibonacci Series Program in Python Leap Year Program in Python Palindrome Program in Python Check Palindrome In Python Calculator Program in Python Armstrong Number Program in Python Python Program to add two numbers Anagram Program in Python Even Odd Program in Python GCD Program in Python Python Exit Program Python Program to check Leap Year Operator Overloading in Python Pointers in Python Python Not Equal Operator Raise Exception in Python Salary of Python Developers in India What is a Script in Python Singleton design pattern in python

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 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.



ADVERTISEMENT
ADVERTISEMENT