Python - Inheritance vs Polymorphism

Python - Inheritance vs Polymorphism

Introduction

Two important terms to understand when learning Python and OOP (object-oriented programming) are inheritance and polymorphism.

Inheritance

Inheritance establishes a relationship between two classes - parent (superclass) and child (subclass).
Child classes keep the attributes and methods of their parent, whilst also adding new attributes or methods of its own. Furthermore, the child class can also override methods of its parent.

Below shows an example:

class NetDevice(object):
    def get_dc(self):
        print("London")
        
class NetDeviceCisco(NetDevice):
    pass
    
class NetDeviceJuniper(NetDevice):
    pass
>>> NetDevice().get_dc()
London
>>> NetDeviceCisco().get_dc()
London
>>> NetDeviceJuniper().get_dc()
London

Polymorphism

Polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like Python. Therefore Polymorphism can be defined as changing the behavior of a superclass from within the subclass.

Below shows an example. As you can see we are changing the get_os_type method from our superclass from within our subclass.

class NetDevice(object):
    def get_dc(self):
        print("London")

    def get_os_type(self):
        print("Unknown")
        
class NetDeviceCisco(NetDevice):
    def get_os_type(self):
        print("IOS")
        
class NetDeviceJuniper(NetDevice):
    def get_os_type(self):
        print("JunOS")
>>> NetDevice().get_dc()
London
>>> NetDevice().get_os_type()
Unknown
>>>
>>> NetDeviceCisco().get_dc()
London
>>> NetDeviceCisco().get_os_type()
IOS
>>>
>>> NetDeviceJuniper().get_dc()
London
>>> NetDeviceJuniper().get_os_type()
JunOS

Subscribe to our newsletter and stay updated.

Don't miss anything. Get all the latest posts delivered straight to your inbox.
Great! Check your inbox and click the link to confirm your subscription.
Error! Please enter a valid email address!