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.
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 :
Lets write definition of these classes. Open python IDLE, create a file Progression.py and copy following code lines in it:
Now we will be creating Arithmetic and Geometric implementation inheriting Progression:
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:
Previous: Method overloading and Operator overloading
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 |
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 |
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)))
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
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:
- 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.
- 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.
Previous: Method overloading and Operator overloading
Tags:
Python
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
ReplyDeleteAivvu chuyên vé máy bay, tham khảo
ReplyDeletesăn vé máy bay giá rẻ đi Mỹ
vé máy bay tết 2021 Vietnam Airline
vé máy bay việt nam đi canada
vé máy bay Việt Nam đi Pháp
giá vé máy bay đi Anh Vietnam Airline
vé máy bay giá rẻ nhất
combo intercontinental đà nẵng
combo nha trang đà lạt
Đặt vé máy bay tại Aivivu, tham khảo
ReplyDeletevé máy bay đi Mỹ tháng nào rẻ nhất
bay từ california về việt nam mất bao lâu
gia ve may bay di Los Angeles
vé máy bay từ canada về việt nam bao nhiêu tiền
Great post very useful info thanks for this post ....
ReplyDeleteCore Java Online Training Hyderabad
Visit us: Java Online Training
Excellent article and this helps to enhance your knowledge regarding new things. Waiting for more updates.
ReplyDeleteData Type In PHP
Boolean In PHP
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.
ReplyDeleteVery informative. Now I got an idea about this topic. thanks for the content.
ReplyDeleteCCNA Network Fundamentals
Learn Networking Step-By-Step
Nice blog...Thanks for commenting…
ReplyDeleteHow to improve the communication skills in English
Ways to improve communication skills in English
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
ReplyDeleteNice Post!!! Thank you for sharing
DevOps Online Training
DevOps Training in Chennai
DevOps Training in Bangalore
Great post. keep sharing such a worthy information.
ReplyDeleteGerman Language Course In Chennai
Amazing Post.Thanks for sharing.
ReplyDeleteFull stack classes in Pune
Well- written. Your explanation is really good. A non-IT person can also easily understand this.
ReplyDeletePython Training course in Delhi
Nice blog, Thanks for giving this information
ReplyDeleteCognizant jobs for Freshers
Cognizant Recruitment
Freshers Jobs
Superb article.
ReplyDeletealso,check Python training in Pune