Inheritance in python

In object-oriented programming, a modular and hierarchical organization of classes and software module is achieved using  inheritance. 
The classes at top in hierarchy is typically described as the base class, parent class, or superclass, while class which extend base class is known as the subclass or child class. The relation between these two class base class ,derived classes or subclass is called "IS-A". Here is the class hierarchy of exception types in python.
Hierarchy of exception types
BasicException class is super class and all classes in below hierarchy are derived classes. BaseException is parent class for child class/subclass keyboardInterrupt.

What inheritance brings in Object oriented programming ? - Re-usability of code. i.e : base class defines common functionality for derived class and allow derived class to focus on specific functionality related to that class.
In order to get holistic picture of inheritance, lets take an example of Numeric Progressions classes. Here Arithmetic progression and Geometric progressions are derived classes and Progression is base class. (Example reference : Data Structure and Algorithm by Goodrich)
The class hierarchy will looks like this :
Hierarchy of progression classes
Lets write definition of these classes. Open python IDLE, create a file Progression.py and copy following code lines in it:
class Progression(object): #Inheriting object class
 def __init__(self, start=0):
   self._current = start

 def _advance(self):
   self._current += 1

 def next(self):# Python 3: def __next__(self)
   #our convention to end a progression
   if self._current is None: 
     raise StopIteration()
   else:
   # record current value to return
     answer = self._current 
     self._advance() 
     return answer 
     
 def __iter__(self):
   return self

 def print_progression(self, n):
   print( ' '.join(str(next(self))
                                        for j in range(n)))
Now we will be creating Arithmetic and Geometric implementation inheriting Progression:
from Progression import Progression
class ArithmeticProgression(Progression): # inherit from Progression
 '''Iterator producing an arithmetic progression.'''
 def __init__(self, increment=1, start=0):
  Progression.__init__(self,start) # initialize base class
  self._increment = increment

 def _advance(self): # override inherited version
  self._current += self._increment

class GeometricProgression(Progression): # inherit from Progression
 '''Iterator producing an geometric progression.'''
 def __init__(self, base=2, start=1):
  super(GeometricProgression,self).__init__(start)
  self._base = base

 def _advance(self): # override inherited version
  self._current *= self._base
In above classes defined . Progression inherit from object class, mother of all in python. Progression class defines constructor to declare current element and various method like incrementing sequence ,
getting next element and printing the sequence. ArithmaticProgression and GeometricProgression are inheriting Progression class and override advance method as per logic of ArithmaticProgression (incremented by constant value) and GeometricProgression (multiplied by constant value).
Sample output: ------------------------------------
>>> p = Progression(4)        #start is initialized with 4
>>> p.print_progression(4)  #for loop will iterate four times and execute next(self) of Progression
4 5 6 7

>>> a = ArithmeticProgression(increment=2, start=3)   #Overwrite default value
>>> a.print_progression(4)  #Overridden _advance() of  ArithmeticProgression executed  
3  5 7 9

>>> g =GeometricProgression( base=3, start=12)  #Overwrite default value
>>> g.print_progression(3) # Overridden _advance() of  GeometricProgression executed and each
                                             # time values are multiplied by 3 using self._current *= self._base 

12 36 108
---------------------------------------------
Notes:
  1.  class Progression(object) vs  class Progression/class Progression() : class Progression(object) is new style of writing class definition while class Progression: is old way of doing this.In order to unify type and class from python 2.2 new style of class definition was introduced. For detail refer this post. 
  2. super(GeometricProgression,self).__init__(start) / How super() got changed in python 3 ?In python 2.x, for initializing member variables of parent class from derived class we need to pass parameters values via calling super(<current_class>, self).__init__(<arguments>). However, form python 3,  <current_class>, self become optional. Refer this for detail.
    Another way of accessing init of parent class by explicitly using class name. i.e : We have used Progression.__init__(self , start) , Progression is base class name.
In order to make backward compatible both old class definition/classical definition of class are still valid in python 3 and so as use of super with class name and self as argument.


Previous: Method overloading and Operator overloading   

15 Comments

  1. Out of many tools, Data scientists require to use the most relevant statistical and algorithm deployment tools to their objectives. It is a thoughtful process to choose the right model since the model plays the key role in bringing valuable insights. data science course syllabus

    ReplyDelete
  2. Great post very useful info thanks for this post ....
    Core Java Online Training Hyderabad
    Visit us: Java Online Training

    ReplyDelete
  3. Excellent article and this helps to enhance your knowledge regarding new things. Waiting for more updates.
    Data Type In PHP
    Boolean In PHP

    ReplyDelete
  4. Python training institute in Pune can be extremely simple and advantageous with ITView Software Training Institute. In spite of the fact that we as a whole realize that there are incalculable Python Training Institutes in Pune however there is something interesting and exceptional about ITView Software Training Institute.

    ReplyDelete
  5. Very informative. Now I got an idea about this topic. thanks for the content.
    CCNA Network Fundamentals
    Learn Networking Step-By-Step

    ReplyDelete
  6. Hi, I read your whole blog. This is very nice. Good to know about the career in. Python Training & Certification , anyone interested can Python Training for making their career in this field.

    ReplyDelete
  7. Great post. keep sharing such a worthy information.
    German Language Course In Chennai

    ReplyDelete
  8. Well- written. Your explanation is really good. A non-IT person can also easily understand this.
    Python Training course in Delhi

    ReplyDelete
Previous Post Next Post