Parameterized Constructor and Destructor Example in Python

Here, we are going to learn about the Parameterized Constructor and Destructor in Python and going to demonstrate the example of Parameterized Constructor and Destructor.
Submitted by Shivang Yadav, on February 15, 2021

Description: Here, we will see a program to see working of parameterized constructor and destructor in Python.

Constructors are the methods of a class that are called at the time or creation of objects. These are used to assign values to members of the class.

Parameterized constructors are the special constructors that take parameters to initialize the members.

Syntax:

Creation: 
	def __init__(self, parameters):
		# body of the constructure...
Calling: 
	className(parameters)

Destructors are the methods those are called when the objects are destroyed. They are used for garbage collection and memory management.

Syntax:

Creation: 
def __del__(self):
        # body of the constructure...

Calling:
	del object

Algorithm:

  • Step 1: Create a Class named Person.
  • Step 2: Create its parameterized constructor to initialize the values of its member function.
  • Step 3: We will print information using printInfo() method.
  • Step 4: At last we will call Destructor to free up memory.

Program to illustrate the parameterized constructor and destructor in Python

class Person:
    def __init__(self,name,age):
        print("Person Created")
        self.name = name
        self.age = age
    def printInfo(self):
        print(self.name,self.age)
    def __del__(self):
        print(self.name,"Object Destroyed")
        
P1=Person("John",46)
P2=Person("Joe",34)
P1.printInfo()
P2.printInfo()
del P1
input()

Output:

Person Created
Person Created
John 46
Joe 34
John Object Destroyed
del
Joe Object Destroyed

Python class & object programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.