Q:

Parameterized Constructor and Destructor Example in Python

belongs to collection: Python class & object programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python class & object programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to add numbers using Objects... >>
<< Constructor Initialization Example in Python...