What is inheritance?
Inheritance allows us to define a sub or child class which inherits functionality from another class, otherwise known as a base class or a parent class.
Inheritance is usually referred to as an Is-A relationship. For example: a car is a vehicle, or a dog is an animal.
Inheritance allows us to reuse code from a class. We wrap common code in one class, then reuse that code in another class.
Inheritance also provides polymorphic behavior, which can be quite powerful.
Inheritance Programs in Python (Example)
Example-1: Create a Child class using Parent class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class GrandParent: def func1(self): print("It is My Grand Parent") class Parent: def func2(self): print("It is My Parent") class Child(GrandParent , Parent): def func3(self): print("It is My Child") ob = Child() ob.func1() ob.func2() ob.func3() |
Example-2:
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Parent(): def first(self): print('Hi Parent!') class Child(Parent): def second(self): print('Hi Child!') ob = Child() ob.first() ob.second() |