Python class inheritance
The word inheritance means :
1: The act of inheriting property.
2: The reception of genetic qualities by transmission from parent to offspring.
3: The acquisition of a possession, condition, or trait from past generations.
Similarly in python Inheritance allows us to define a class that inherits all the methods and properties from another class.
Parent class: is the class being inherited from, also called a base class.Child class: is the class that inherits from another class, also called derived class.
Example :
First we have to create a parent class, any class can be a parent class.
Here the class Animal is parent class, Dog and Cat are ,child class.
As Dog and Cat comes under the category Animal,The objects /Characters
Of animal class can be used on any animal.
like all animal will have some common factors like speak,eating,sleeping ..
these will be created as objects of Animal class .And while creating child class
it will be having specific qualities of that particular species .like monkey have
an extra object/character as it can climb tree. so the child class Monkey will be
having this species specific quality/feature/object mentioned .
Benefits of Inheritance:
Inheritance helps in code reuse
.
The child class may use the code defined in the
parent class without
re-writing it. Inheritance can save time and effort as the main
code
need not be written again. Inheritance provides a clear model structure
which is easy to understand.
How to add __init__() Function to child class?
Points to note:
-The _init_() function will be called automatically every-time we create a new object.
-The child's __init__()
function overrides the inheritance of the parent's
__init__()
function.
i.e when we directly add __init__() in in our child class it will bypass the the __init__() of parent class , so the child class won't be getting data /values of parent class __init__().
To avoid this situation we have to add a call to the
parent's __init__()
function.
__init__()
function.