Featured

    Featured Posts

Python OOPS Tutorial 4:Destructor in Python


Garbage Collection In Python

§  In the given figure obj is reference variable which is pointing to the object.

§  In this time this object is still being referenced by obj variable. Once we assign the 
   None into the object reference, then the object will be unused because it is not 
    pointing by any reference variable at the moment.

§  So now who is responsible to delete this unused object. 

§  In old languages like C++, programmer is responsible for both creation and  
   destruction of objects. Usually programmer taking very much care while creating 
   object, but neglecting destruction of useless objects. Because of his reflectance, total     memory can be filled with useless objects which creates memory problems and total 
   application will be down with Out of memory error.   

 §  But in Python, programmer is not responsible to delete unused object

 §  The python has given an assistant for this work which is always running in the  
       background to destroy useless objects. Because this assistant the chance of failing  
       Python program with memory problems is very less. This assistant is nothing but  
       Garbage Collector.

 v For example, suppose you ordered coffee in the office. You will need to throw a cup 
        after drinking coffee. after drinking coffee cup become unused so who is reasonable 
       to clean-up to this unused cup for this company has given assistant to perform clean- 
       up activity This assistant is nothing but Sweeper. 

 v In company employee is not reasonable to perform clean-up activity. sweeper is 
        taking -care of this clean-up activity.


Hence the main objective of Garbage Collector is to destroy useless objects. 
§  When object is eligible for GC.
§  If an object does not have any reference variable then that object is eligible for Garbage Collection.

How to enable and disable Garbage Collector in our program:
      §  By default, Garbage collector is enabled, but we can disable based on our 
        requirement. In this context we can use the following functions of gc module. 

1.     gc.isenabled()     Returns True if GC enabled
2.     gc.disable()      To disable GC explicitly
3.     gc.enable()      To enable GC explicitly

Example:
import gc
print(gc.isenabled())#The Output:True
gc.disable()
print(gc.isenabled())#The Output:False
gc.enable()
print(gc.isenabled())#The Output:True


Destructor In Python
§  As we know that if you want to perform any activity at the time of object creation 
   then we should go for constructor like that If you want to perform any activity at the 
   time of object destruction then we should go for destructor.

§  Destructor is a special method that are executed as part of the object destruction.

§  In a single word Destructor is a special member method which will be called  '   
   automatically whenever object is destroy.

§  The name of the Destructor should be __del__(self).

Purpose of Constructor:
§  The Purpose of destructor is not to destroy object and it is just to perform cleanup activities

Effects of the del command
    ü Removing a variable name from the scope using del v, or removing an object from a 
        collection using del v[item] or del[i:j], or removing an attribute using del v.name, or 
        any other way of removing references to an object, does not trigger any destructor 
        calls or any memory being freed in and of itself. Objects are only destructed when 
        their reference count reaches zero.

Example:-
import gc
class Test:
    def __init__(self):
        print('Initialized')
        self.a=10
        self.b=20
    def __del__(self):
        print('Destructed')
    def display(self):
        print('hello test')

#Create an Object
t1=Test()
del t1.a
t1.display()
Output:
Initialized
hello test
Destructed

Example:-
import gc
class Test:
    def __init__(self):
        print('Initialized')
    def __del__(self):
        print('Destructed')
   
#Create an Object
t1=Test()
Output:
Initialized
Destructed
Example:-
import gc
class Test:
    def __init__(self):
        print('Initialized')
    def __del__(self):
        print('Destructed')
    def display(self):
        print('hello test')
#Create an Object
t1=Test()
t1.display()

Output:
Initialized
hello test
Destructed

Reference Counting
    §  Every time an object is referenced (e.g. assigned to a variable), its reference count is
       automatically increased. When it is dereferenced (e.g. variable goes out of scope), its     reference count is automatically decreased.
       
 §  When the reference count reaches zero, the object is immediately destroyed and the
        memory is immediately freed. Thus, for the majority of cases, the garbage collector
        is not even needed.

import gc
class Test:
    def __init__(self):
        print('Initialized')
    def __del__(self):
        print('Destructed')

#Create an Object
t1=Test()
t2=t1
t3=t2
del t1 
time.sleep(5) 
print("object not yet destroyed after deleting t1")
del t2
time.sleep(5)
print("object not yet destroyed even after deleting t2") 
print("I am trying to delete last reference variable...")
del t3



Example
import gc
import time
class Test:
    def __init__(self):
        print('Initialized')
    def __del__(self):
        print('Destructed')
   
#Create an Object
list=[Test(),Test(),Test()]
del list

Output:
Initialized
Initialized
Initialized
Destructed
Destructed
Destructed

Viewing the refcount of an object
ü sys module contains getrefcount() function for this purpose.

sys.getrefcount(objectreference)

import sys
class Test:
    pass

t1=Test()
t2=t1
t3=t1
t4=t1
print(sys.getrefcount(t1))   

Output:
5








author

Author Name

Author Description!

Get Free Email Updates to your Inbox!

Post a Comment

www.CodeNirvana.in

Powered by Blogger.

About

Site Links

Popular Posts

Translate

Total Pageviews