OOP — Inheritance and Polymorphism in Python

Jayashree domala
Level Up Coding
Published in
4 min readOct 11, 2020

--

Photo by Meagan Carsience on Unsplash

A guide to knowing in details about the object-oriented programming concept of inheritance and polymorphism in Python

Inheritance is a way of forming new classes using classes that have already been defined. The advantage is this is the ability to re-use code and reduce the complexity of the program.

Inheritance

We start off by making a base class called ‘animal’ which does not take any arguments and just prints a statement using the “init” method. Then 2 more methods are created.

>>> class Animal():
def __init__(self):
print("Animal class created")
def guess_who(self):
print("I am an animal")
def sleep(self):
print("I am sleeping")
>>> my_animal = Animal()
Animal class created
>>> my_animal.sleep()
I am sleeping

You can see the methods of the instance created.

Now new classes if made can inherit some methods of this base class if needed. Like we need a ‘Cat’ class then some features of the animal class are useful for the dog class. So we can inherit the base class “Animal”. We pass “Animal” as an argument while creating the derived class. Then define a “init” method where we call “Animal__init__” method. So this way we create an instance of Animal class when we create an instance of the “Cat” class. And you will observe that the methods of “Animal” class will be derived by the “Cat” class. You can also overwrite the existing methods. Just use the same name. Adding new methods is also possible.

>>> class Cat(Animal):
def __init__(self):
Animal.__init__(self)
print("Cat class created")
def guess_who(self):
print("I am a cat")
def meow(self):
print("MEOWW!")
>>> my_cat = Cat()
Animal class created
Cat class created
>>> my_cat.guess_who()
I am a cat
>>> my_cat.meow()
MEOWW!

You can see the methods for the instance created of the “Cat” class.

Polymorphism

It refers to the way in which different object classes can share the same method name. We create two classes “Dog” and “Cat” which have the same method “speak”. When we call each object’s speak method, it return a result that is unique to the object.

>>> class Doggy():
def __init__(self,name):
self.name = name
def speak(self):
return self.name + " says WOOF"
>>> class Catty():
def __init__(self,name):
self.name = name
def speak(self):
return self.name + " says MEOW"
>>> my_dog = Doggy("Buzo")
>>> my_cat = Catty("Tim")
>>> print(my_dog.speak())
Buzo says WOOF
>>> print(my_cat.speak())
Tim says MEOW

So notice that “my_dog” and “my_cat” have the same method name called “speak” but they have different types of class as seen.

>>> for pet in [my_dog, my_cat]:
print(type(pet))
print(type(pet.speak()))
print(pet.speak())
<class '__main__.Doggy'>
<class 'str'>
Buzo says WOOF
<class '__main__.Catty'>
<class 'str'>
Tim says MEOW

Abstract classes and inheritance

Abstract classes are never expected to be instantiated. An instance of such a class is never expected to be made. It is designed to only serve as a base class.

>>> class Animal():
def __init__(self,name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement this abtract method")
>>> my_animal = Animal("Tia")>>> my_animal.speak()---------------------------------------------------------------------------
NotImplementedError Traceback (most recent call last)
<ipython-input-28-ed4198de9ea6> in <module>
----> 1 my_animal.speak()
<ipython-input-26-977e7051d647> in speak(self)
5
6 def speak(self):
----> 7 raise NotImplementedError("Subclass must implement this abtract method")
NotImplementedError: Subclass must implement this abtract method

So now an error is raised since this class was never supposed to be instantiated. This is an abstract class because in the base class it is not doing anything and expects you to inherit this class and overwrite the method. Infact, we need to create a subclass and implement this method which we will see below. Note that here we do not have to class the “init” method.

>>> class Dog(Animal):
def speak(self):
return self.name + " says Woof!"
>>> class Cat(Animal):
def speak(self):
return self.name + " says Meow!"
>>> jim = Dog("Jim")
>>> tim = Cat("Tim")
>>> print(jim.speak())
Jim says Woof!
>>> print(tim.speak())
Tim says Meow!

Refer to the notebook here.

Beginner-level books to refer to learn Python:

Advance-level books to refer to learn Python:

Reach out to me: LinkedIn

Check out my other work: GitHub

--

--

Self-driven woman who wishes to deliver creative and engaging ideas and solutions in the field of technology.