Saturday, 5 December 2015

Python: __del()__ method

‘__del__’ method is called when the instance is about to be destroyed. This is also called as destructor.


Employee.py
class Employee:
 """ Blue print for all employees """
 # Class level variables
 noOfEmployees=0
 organization="abcde corporation"
  
 def __init__(self, id=-1, firstName="Nil", lastName="Nil"):
  self.id = id
  self.firstName = firstName
  self.lastName = lastName
  Employee.noOfEmployees+=1
  
 def displayEmployee(self):
  print(self.id, self.firstName, self.lastName)
  
 def __del__(self):
  className = self.__class__.__name__
  print(className, self.id, "object destroyed")
  
emp1 = Employee(id=1, firstName="Hari Krishna", lastName="Gurram")
emp1.displayEmployee()

emp2 = Employee(id=3, firstName="PTR")
emp2.displayEmployee()

$ python3 Employee.py 
1 Hari Krishna Gurram
3 PTR Nil
Employee 3 object destroyed
Employee 1 object destroyed

To ensure proper deletion of the base class part of the instance, child class __del__ must call parent __del__ method.

MultipleInheritance.py
class A:
 def printA(self):
  print("I am in A")
  
 def __del__(self):
  print("Instance of A freed")
  
class B(A):
 def printB(self):
  print("I am in B")
  
 def __del__(self):
  super(B, self).__del__()
  print("Instance of B freed")
    
class C(B):
 def printC(self):
  print("I am in C")

 def __del__(self):
  super(C, self).__del__()
  print("Instance of C freed")
  
class D(C):
 def printD(self):
  print("I am in D")
  
 def __del__(self):
  super(D, self).__del__()
  print("Instance of D freed")
  
obj=D()
obj.printA()
obj.printB()
obj.printC()
obj.printD()

$ python3 MultipleInheritance.py 
I am in A
I am in B
I am in C
I am in D
Instance of A freed
Instance of B freed
Instance of C freed
Instance of D freed



Previous                                                 Next                                                 Home

No comments:

Post a Comment