OOPs - Inheritance
Inheritance in Python
In OOPs when one class extends or inherit the properties of another class then it is called as Inheritance. The class from which we inherit the property is called Parent class and another one is called as child class. By property we means methods and data.
To inherit parent into child we pass the parent class as a parameter into the child class. Lets see how -
class Animal:
def walking():
print("Animal walking")
class Dog(Animal):
def speak():
print("Barking")
d = Dog()
d.speak() # Barking
d.walking() # Animal walking
As we can see that we have not defined the walking function in Dog class but we can still use it because we inherited it from Animal class.
Types of Inheritance :
Single level Inheritance : In this type there is only one parent class and one child class. Above program is the example of this.
Multi level Inheritance : In this type of inheritance there are multiple parent and multiple child classes. Suppose we have three classes and B inherit A and C inherit B then it is multilevel.
E.g. -
class A:
def f1():
return True
class B(A):
def f2():
return False
class C(B):
def f3():
return True
In this example we can see the multilevel inheritance. Now class C can inherit the properties of class A also.
Multiple Inheritance : In this type we have multiple parent class but single child class. Single class will inherit the properties from multiple parent classes.
E.g. -
class A():
#code
class B():
#code
class C(A, B):
#code
Method Overriding :
In inheritance there is a common scenario that can be seen as sometimes there are the same name of methods in both parent and child class. Now the problem is that when the child class object call the method then which one will execute? Well simple execute the one which is close. So child class method will override the parent class method.
class A:
def fun():
print("This is A")
class B(A):
def fun():
print("This is B")
a = A()
b = B()
b.fun() # This is B
a.fun() # This is A
So we can see that when both parent and child classes have same method name then they will execute the method they own. Method of child class will override the parent class.
Comments
Post a Comment