python tutorial - Inheritance in Python - learn python - python programming
What is Inheritance?
- Inheritance is used to specify that one class will get most or all of its features from its parent class. It is a feature of Object Oriented Programming.
- It is a very powerful feature which facilitates users to create a new class with a few or more modification to an existing class.
- The new class is called child class or derived class and the main class from which it inherits the properties is called base class or parent class.
- The child class or derived class inherits the features from the parent class, adding new features to it. It facilitates re-usability of code.
Python Inheritance Syntax:
- Derived class inherits features from the base class, adding new features to it. This results into re-usability of code.
Example of Inheritance in Python:
- To demonstrate the use of inheritance, let us take an example.
- A polygon is a closed figure with 3 or more sides. Say, we have a class called Polygondefined as follows.
- This class has data attributes to store the number of sides, n and magnitude of each side as a list, sides.
- Method inputSides() takes in magnitude of each side and similarly, dispSides() will display these properly.
- A triangle is a polygon with 3 sides. So, we can created a class called Triangle which inherits from Polygon.
- This makes all the attributes available in class Polygon readily available in Triangle. We don't need to define them again (code re-usability). Triangle is defined as follows.
- However, class Triangle has a new method findArea() to find and print the area of the triangle.
- Here is a sample run.
- We can see that, even though we did not define methods like inputSides() or dispSides()for class Triangle, we were able to use them.
- If an attribute is not found in the class, search continues to the base class. This repeats recursively, if the base class is itself derived from other classes.
- The name BaseClassName must be defined in a scope containing the derived class definition.
- You can also use other arbitrary expressions in place of a base class name.
- This is used when the base class is defined in another module.
Python Inheritance Example
- Let's see a simple python inheritance example where we are using two classes: Animal and Dog. Animal is the parent or base class and Dog is the child class.
- Here, we are defining eat() method in Animal class and bark() method in Dog class.
- In this example, we are creating instance of Dog class and calling eat() and bark() methods by the instance of child class only.
- Since, parent properties and behaviors are inherited to child object automatically, we can call parent and child class methods by the child instance only.