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

Here, we will figure out how to execute destructor and constructors utilizing del() and init() in Python?

To execute a constructor, we use init() and to actualize a destructor, we use del() in python.

Program:

Output:

by utilizing the str technique,

In this program, we are executing str work utilizing str(). This capacity restores a string at whatever point we pass class’ article to print() work.

# 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        :121
Enter Name      :Kishan
Enter Gender:Male
Enter City      :Raipur
Enter Salary:75000
Id              : 121
Name    : Kishan
Gender  : Male
City    : Raipur
Salary  : 75000
[121,Kishan,Male,Raipur,75000]
Object Destroyed.

Leave a Comment

error: Alert: Content is protected!!