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
Amazing experience on reading your article. It is really nice and informative.
ReplyDeletePython Training in Chennai
Python Training in Anna Nagar
JAVA Training in Chennai
Hadoop Training in Chennai
Selenium Training in Chennai
Python Training in Chennai
Python Training in Velachery
The development of artificial intelligence (AI) has propelled more programming architects, information scientists, and different experts to investigate the plausibility of a vocation in machine learning. Notwithstanding, a few newcomers will in general spotlight a lot on hypothesis and insufficient on commonsense application. machine learning projects for final year In case you will succeed, you have to begin building machine learning projects in the near future.
DeleteProjects assist you with improving your applied ML skills rapidly while allowing you to investigate an intriguing point. Furthermore, you can include projects into your portfolio, making it simpler to get a vocation, discover cool profession openings, and Final Year Project Centers in Chennai even arrange a more significant compensation.
Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account.
The Nodejs Projects Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training
Great efforts put to publish these kinds of articles that are very useful to know. I’m thoroughly enjoying your blog. And Good comments create great relations. You’re doing an excellent job. Keep it up.
ReplyDeleteMagento Development Training Course in Chennai Zuan Education
Selenium Training Course in Chennai Zuan Education
Thanks for sharing such a most informative blog.... Waiting for the new updates...
ReplyDeleteDigital Marketing Course In Kolkata
Web Design Course In Kolkata
SEO Course In Kolkata
Usually I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great job Man learn Python Online Course
ReplyDeleteOut 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