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.

Image for post

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.

#inheritance #polymorphism #python #coding #object-oriented

OOP — Inheritance and Polymorphism in Python
1.80 GEEK