Inheritance
In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object or class, retaining similar implementation
OOP provides inheritance in between classes so that the classes can share methods or attributes which are already defined.
Imagine there is a class Talents with methods describing each talent.
Input
class Talents:
def athletic(self):
print('You are an athlete')
Now we will create an instance father by calling the talents class. And obviosuly, this will mean that the child of this father will have a high chance of also having an athletic talent.
Input
father = Talents()
father.athletic()
Output
You are an athlete
Now, we will make an instance LuckyChild and that he has inherited father's gifted athletic talent.
Input
class LuckyChild(Talents):
pass
Input
child1 = LuckyChild()
child1.athletic()
Output
You are an athlete
Without having a method inside the class, instance child1 has an athletic talent due to his inheritance.
In fact, child1 has an year-younger sibiling, child2, who also aspires to be an athlete one day. Unluckily, he did not inherit father's athleticism.
Input
class UnluckyChild:
pass
Input
child2 = UnluckyChild()
child2.athletic()
Output
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-9-b7a2d03bc687> in <module>
1 child2 = UnluckyChild()
----> 2 child2.athletic()
AttributeError: 'UnluckyChild' object has no attribute 'athletic'
Inherit would be somewhat non-sensical, if the heirs can exert different abilities beside those they inherited. Now, we will see a case of child3, a younger brother of child2, who is not only athletic but also academic.
Input
class LuckierChild(Talents):
def academic(self):
print('You are a scholar')
Input
child3 = LuckierChild()
child3.athletic()
child3.academic()
Output
You are an athlete
You are a scholar
Child 3 surely can be an athlete or a scholar one day.
Class inheritance can be replaced by simply copying and pasting the identical method into different classes. However, this will create duplicative codes with same function which is insufficient in maintaining code concise and succint. However, using class inheritance, programmers can easily use pre-defined methods and features with least amount of codes.