Object Oriented Concepts: Inheritance

In this post we will be discussing

  1. What inheritance is?
  2. Why do we need inheritance?
  3. Types of Inheritance

Inheritance in programming is acquiring attributes or properties from the parent class. With inheritance we can re-use code this helps us to create and maintain applications.

Assume you have an application where customer can customize their furniture. They can decide the shape, the size, color and material. Once a user logs into your website the user can then select shape of the furniture to implement the class without inheritance it would look like this:

class Circle:
    def area(self,radius):
        return pi * radius * radius

class Rectangle:
    def area(self,length, breadth):
        return length * breadth

Both classes implement a method called “area” and return area of the shape. But we can see there are 2 different class implementing the same Area method.

We know that both classes Circle as well as Rectangle are Shapes, and they have a relationship between them; Circle is a Shape and Rectangle is a Shape, to denote this relation in UML

Where the Base is the Shape class and derived is the Child class.

Following is the code example

""" Inheritance Implementation"""
from math import pi


class Shape:
    def area(self,*args):
        return 


class Circle(Shape):
    def area(self,radius):
        return pi * radius * radius 


class Rectangle(Shape):
    def area(self, length, breadth):
        return length * breadth

Types of Inheritance are as follows:

Multiple inheritance example is given below(when class has multiple parents )

class User:
    def __init__(self, user_name):
        self._user_name = user_name
    def print_user(self):
        print("User name is {}".format(self._user_name)
class Address:
    def __init__(self,address):
        self._address = address
    def address(self):
        print("User Address is {}".format(self._address)

class Customer(User, Address):
    pass

Multi-level Inheritance

class A:
  ....
class B(A):
  ....
class C(B):

This was a gist of inheritance, hope this helpful

Happy Coding

Stay Safe

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s