Explain Inheritance in python.

Inheritance :
  • Inheritance enables us to define a class that takes all the functionality from a parent class and allows us to add more.
  • Classes can inherit from other classes. A class can inherit attributes and behavior methods from another class, called the superclass.
  • A class which inherits from a superclass is called a subclass, also called heir class or child class. Superclasses are sometimes called ancestors as well.
  • Syntax :
class DerivedClass(BaseClass) :
   body_of_derived_class
  • A derived class inherits features from the base class, adding new features to it. This results in re-usability of code.
  • If an attribute is not found in the class, the search continues to the base class. This repeats recursively if the base class is derived from other classes.
  • Ex :
class Polygon:
   def __init__(self, no_of_sides):
       self.n = no_of_sides
       self.sides = [0 for i in range(no_of_sides)]


   def inputSides(self):
       self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)]


   def dispSides(self):
       for i in range(self.n):
           print("Side",i+1,"is",self.sides[i])


class Triangle(Polygon):
   def __init__(self):
       Polygon.__init__(self,3)


   def findArea(self):
       a, b, c = self.sides
       # calculate the semi-perimeter
       s = (a + b + c) / 2
       area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
       print('The area of the triangle is %0.2f' %area)


>>> t = Triangle()
>>> t.inputSides()
Enter side 1 : 3
Enter side 2 : 5
Enter side 3 : 4
>>> t.dispSides()
Side 1 is 3.0
Side 2 is 5.0
Side 3 is 4.0
>>> t.findArea()
The area of the triangle is 6.00
  • Method Overriding :
    • It is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its parent classes.
    • In the above example, __init__() method was defined in both classes, Triangle as well Polygon. When this happens, the method in the derived class overrides that in the base class. This is to say, __init__() in Triangle gets preference over the same in Polygon.
    • Generally when overriding a base method, we tend to extend the definition rather than simply replace it. The same is being done by calling the method in base class from the one in derived class (calling Polygon.__init__() from __init__() in Triangle).
    • A better option would be to use the built-in function super(). So, super().__init(3) is equivalent to Polygon.__init__(self,3) and is preferred.
  • isinstance() and issubclass() :
    • Two built-in functions isinstance() and issubclass() are used to check inheritances.
    • isinstance() returns True if the object is an instance of the class or other classes derived from it.
    • Each and every class in Python inherits from the base class object.
    • Ex :
>>> isinstance(t,Triangle)
True
>>> isinstance(t,Polygon)
True
>>> isinstance(t,int)
False
>>> isinstance(t,object)
True
>>> issubclass(Polygon,Triangle)
False
>>> issubclass(Triangle,Polygon)
True
>>> issubclass(bool,int)
True
  • Types :
    • Single Inheritance
    • Multiple Inheritance
    • Hierarchical Inheritance
    • Multilevel Inheritance
    • Hybrid Inheritance (also known as Virtual Inheritance)


Multiple Inheritance :
  • In multiple inheritance, the features of all the base classes are inherited into the derived class.
  • Syntax :
class Base1:
   pass
class Base2:
   pass
class MultiDerived(Base1, Base2):
   pass

  • MRO (Method Resolution Order) :
    • The order in which base classes are searched when looking for a method is often called the Method Resolution Order.
    • In the multiple inheritance scenario, any specified attribute is searched first in the current class. If not found, the search continues into parent classes in depth-first, left-right fashion without searching same class twice.
    • So, in the above example of MultiDerived class the search order is [MultiDerived, Base1, Base2, object]. This order is also called linearization of MultiDerived class and the set of rules used to find this order is called Method Resolution Order (MRO).

Comments

Post a Comment

Popular posts from this blog

What is composite key?

What are the different data types in Python?

What is __repr__ function?