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








Python OOPS Tutorial 2:Python Classes and Objects


What is a class?
Answer: -

class

 §  A class is a specification or blue print or template of an object.

 §  Class is a logical construct; an object has physical reality.
 §  Class is a structure
 §  Binding the data with its related and corresponding functions.
 §  Class is the base for encapsulation.
 §  Class is a user defined data type in java.
 §  Class will act as the base for encapsulation and implement the concept of 
       encapsulation through objects.
 § Any java applications look like collection of classes but whereas c- application looks 
       like collection of functions.
 §  Class contains variables and methods.

Object

 §  Objects are key to understanding object-oriented technology. Look around right now 
       and you will find many examples of real-world objects: your dog, your desk, your  
       television set, your bicycle etc.

 §  Real-world objects share two characteristics. They all have state and behaviour.

 §  Object is nothing but instance (dynamic memory allocation) of a class.

 §  The dynamic memory allocated at run time for the members [non-static variables] of 
       the class is known as object.

Object:  Object is an instance of class, object has state and behaviours.

An Object in java has three characteristics:
  ·       State
  ·       Behavior
  ·       Identity


State:  Represents data (value) of an object.

What is state of the Object?

 ü The data present inside object of a class at that point of time is known as state of 
     the object
  Behaviour:  

Ø Represents the behavior (functionality) of an object such as deposit, withdraw etc.

What is behavior of the object? 

ü  The functionalities associated with the object => Behavior of the object. 

ü  The state of the object changes from time-to-time depending up on the 
     functionalities that are executed on that object but whereas behavior of the object 
     would not change.

Identity:  
Ø Object identity is typically implemented via a unique ID. The value of the ID is not 
    visible to the external user. But it is used internally by the PVM to identify each 
    object uniquely.

Question: -

 What Object Contains?

Answer: -  

  Ø Object of any class contains only data.

  Ø Apart from the data object of a class would not contains anything else. 

  Ø Object of a class would not contain any functionalities or logic.

  Ø Thus object of a class would be representing only data and not represent logic.


Question: -
 What is state of the Object?

Answer: -  
 The data present inside object of a class at that point of time is known as   state of the  
   object. 

Question: -
 What is behaviour of the object? 

Answer: -  
The functionalities associated with the object => Behaviour of the object.
The state of the object changes from time-to-time depending up on the   functionalities that are executed on that object      but whereas behaviour of the object would not change.

How to Define a class?

 §  We can write a class to represent properties (attributes) and actions (behaviour) of object.

 §   Properties can be represented by variables.

 §   Actions can be represented by Methods.

 §  We can define a class by using class keyword.

Syntax:
 
class className:
       ''' documenttation string '''  
               variables:instance variables,static and local variables  
      methods: instance methods,static methods,class methods  
 
§  Documentation string represents description of the class. Within the class doc string 
  is always optional. We can get doc string by using the following 2 ways.

print(classname. __doc__)
help(classname)

Syntax to create object In Python:

 referencevariable = classname()

What is a Reference variable?

§     Reference variable is a variable which would be representing the address of the 
     object.
  §    Reference will act as a pointer and handler to the object.
  §    Since reference variable always points an object.
§  In practice we call the reference variable also as an object.
§     By using reference variable, we can access properties and methods of object.
Example: -

§  Suppose there is a class named Person, then see how to create its object.
p = Person ()



§  Suppose there is a class named Customer, then see how to create its object.
   c=Customer ()


class Car
    # class attribute    
    Type1 = "Four wheeler" 
    # instance attribute   
    def __init__(self, name, old):
        self.name = name
        self.old = old

# instantiate the Car class
Maruti = Car("Maruti", 14)
Tata = Car("Tata", 13)

# access the class attributes
print("Maruti is a {}".format(Maruti.__class__.Type1))
print("Tata is also a {}".format(Tata.__class__.Type1))

# access the instance attributes
print("{} is {} years old".format( Maruti.name, Maruti.old))
print("{} is {} years old".format( Tata.name, Tata.old)) 
  
Output
Maruti is a Four wheeler
Tata is also a Four wheeler
Maruti is 14 years old
Tata is 13 years old


There are a few things to note when looking at the above example.
§  The class is made up of attributes (data) and methods (functions)

§  Attributes and methods are simply defined as normal variables and functions

§  As noted in the corresponding docstring, the __init__() method is called the initializer. It's equivalent to the constructor in other object-oriented languages, and is the method that is first run when you create a new object, or new instance of the class.

§  Attributes that apply to the whole class are defined first, and are called class attributes.

§  Attributes that apply to a specific instance of a class (an object) are called instance attributes. They are generally defined inside __init__(); this is not necessary, but it is recommended (since attributes defined outside of __init__() run the risk of being accessed before they are defined).



www.CodeNirvana.in

Powered by Blogger.

About

Site Links

Popular Posts

Translate

Total Pageviews