Python Destructor
Destructor is a special method used to delete class object.
- Destructor name must ne _ _ del _ _()
#program to define a destructor
class Employee_data :
def __del__(self):
print("destroying object")
- Destructor is called when an object is getting destroyed.
#program
class Employee_data :
def __init__(self):
print("This is a Python Constructor, called at Object creation Time")
def __del__(self):
print("destroying object")
Emp_data_1 = Employee_data()
Emp_data_2 = Employee_data()
#Output
This is a Python Constructor, called at Object creation Time
This is a Python Constructor, called at Object creation Time
destroying object # destructor called during destroying object_1
destroying object # destructor called during destroying object_2
- Objects get destroyed during application exit, calling destructor with object will not destroy object
#program
class Employee_data :
def __init__(self):
print("This is a Python Constructor, called at Object creation Time")
def dis(self):
print("hello, I am alive")
def __del__(self):
print("destroying object")
Emp_data_1 = Employee_data() # creating object
Emp_data_1.__del__() # calling destructor
Emp_data_1.dis() # calling a method with object used to call destructor
Emp_data_2 = Employee_data()
#Output
This is a Python Constructor, called at Object creation Time
destroying object
hello, I am alive
This is a Python Constructor, called at Object creation Time
destroying object
destroying object
- Destructor will take "self" as default parameter
#program
class Employee_data :
def __init__(self, name): # constructor accepts value as parameter
self.name = name
self.website = "www.salahtutorials.com"
print("This is a Python Constructor, called at Object creation Time")
def display(self):
print("Name :", self.name)
print("website :", self.website)
def __del__(self):
print("destroying object")
Emp_data_1 = Employee_data("Techno Xpresss") # object_1 created
Emp_data_2 = Employee_data("Er M S Dandyan") # object_2 created
Emp_data_1.display()
Emp_data_2.display()
#Output
This is a Python Constructor, called at Object creation Time
This is a Python Constructor, called at Object creation Time
Name : Techno Xpresss
website : www.salahtutorials.com
Name : Er M S Dandyan
website : www.salahtutorials.com
destroying object # destructor called during destroying object_1
destroying object # destructor called during destroying object_2
Comments
Post a Comment