Explain Inheritance in Python with an example
What is Inheritance?
In the object oriented programming, inheritance is a powerful feature. Inheritance provide us to define the class which will take all the function from parent class and allow us to add more. Python support inheritance even multiple inheritance. It can introduce a new class with little or without any modification of exiting class. The new class is called child class and the base from which it inherits is called parent class.
Some of the major features of inheritance in Python is how the parent class and child class work, how to override method and attribute, how to use super function and multiple inheritance.
Parent class create a pattern from which child or subclass based on. Through inheritance, parent class allow us to create child class without write same code every time. Parent class allow us to made any class within it, so that rather than template all class are fully functionally in their own right.
For example: DEPARTMENT is a class which has some attribute and method.This class has some distinct properties also called attribute like DEPT_NAME, DEPT_MANAGER, DEPT_LOCATION and WORK_SCHEDULE.We can have method on this class.
Child or subclass
Child class will inherit from the parent class. Each subclass or child class will be able to use the method and variant of the parent class.
Let’s continue with DEPARTMENT example. Now IT_DEPT consisting of various skill set like Desktop Support, Application Support, and Network Support. So if we extend DEPARTMNET class to create another class called DEPT_ROLE which is subclass. It will automatically have DEPT_NAME, DEPT_MANAGER, DEPT_LOCATION and WORK_SCHEDULE. No need to declare those attribute separately
Overriding parent method:
Now let’s say DEPARTMENT class has a method or function called DEPT_TASK. Which prints /outputs department work area like fixing computer issue or s/w problem or maintain office space health safety, building electricals etc.
Since we have extended DEPARTMENT class as IT_DEPT we could override DEPT_TASK for specific IT related work like fixing n/w issue or fixing laptop problem etc.
When one class can inherit attributes and method from more than one parent class than it is called multiple inheritance. This can help programme to reduce dismissal but sometime it create certain complexity that will be depend on overall program deign.