Python | Example to implement destructor and constructors using __del__() and __init__()

Here, we are going to learn how to implement destructor and constructors using __del__() and __init__() in Python?
Submitted by Pankaj Singh, on November 16, 2018

To implement a constructor, we use __init()__ and to implement a destructor, we use __del()__ in python.

Program:

class Employee:
    def __init__(self): #Constructor
        self.__id = 0
        self.__name = ""
        self.__gender = ""
        self.__city = ""
        self.__salary = 0
        print("Object Initialized.")
    def __del__(self): #Destructor
        print("Object Destroyed.")
    def setData(self):
        self.__id=int(input("Enter Id\t:"))
        self.__name = input("Enter Name\t:")
        self.__gender = input("Enter Gender:")
        self.__city = input("Enter City\t:")
        self.__salary = int(input("Enter Salary:"))
    def showData(self):
        print("Id\t\t:",self.__id)
        print("Name\t:", self.__name)
        print("Gender\t:", self.__gender)
        print("City\t:", self.__city)
        print("Salary\t:", self.__salary)


def main():
    #Employee Object
    emp=Employee()
    #emp.setData()
    emp.showData()

if __name__=="__main__":
    main()

Output

Object Initialized.
Id              : 0
Name    :
Gender  :
City    :
Salary  : 0
Object Destroyed.

by using __str__ method

In this program we are implementing str function using __str__(). This function returns a string whenever we pass class's object to print() function.

# employee class code in Python
# class definition
class Employee:
	def __init__(self): #Constructor
		self.__id = 0
		self.__name = ""
		self.__gender = ""
		self.__city = ""
		self.__salary = 0
		print("Object Initialized.")

	def __del__(self): #Destructor
		print("Object Destroyed.")

	def setData(self):
		self.__id=int(input("Enter Id\t:"))
		self.__name = input("Enter Name\t:")
		self.__gender = input("Enter Gender:")
		self.__city = input("Enter City\t:")
		self.__salary = int(input("Enter Salary:"))

	def __str__(self):
		data = "["+str(self.__id)+","+self.__name+","+self.__gender+","+self.__city+","+str(self.__salary)+"]"
		return data

	def showData(self):
		print("Id\t\t:",self.__id)
		print("Name\t:", self.__name)
		print("Gender\t:", self.__gender)
		print("City\t:", self.__city)
		print("Salary\t:", self.__salary)


def main():
	#Employee Object
	emp=Employee()
	emp.setData()
	emp.showData()
	print(emp)

if __name__=="__main__":
	main()

Output

Object Initialized.
Enter Id        :101
Enter Name      :Pankaj
Enter Gender:Male
Enter City      :Delhi
Enter Salary:70000
Id              : 101
Name    : Pankaj
Gender  : Male
City    : Delhi
Salary  : 70000
[101,Pankaj,Male,Delhi,70000]
Object Destroyed.

Python class & object programs »



Related Programs



Comments and Discussions!

Load comments ↻





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