
Polymorphism can be carried out through inheritance, with subclasses making use of base class methods or overriding them. This allows functions to use objects of any of these polymorphic classes without needing to be aware of distinctions across the classes.
OOP PYTHON INHERITANCE CODE
So, it provides flexibility and loose coupling so that code can be extended and easily maintained over time. This permits functions to use entities of different types at different times. Polymorphism is an important feature of class definition in Python that is utilized when you have commonly named methods across classes or subclasses. If a subclass try to inherits methods or data from another subclass then it will through an error as we see when Dog class try to call swatstring() methods from that cat class, it throws an error(like AttributeError in our case). In the above example, we see the command attributes or methods we put in the parent class so that all subclasses or child classes will inherits that property from the parent class. In Python, constructor of class used to create an object (instance), and assign the value for the attributes.Ĭonstructor of subclasses always called to a constructor of parent class to initialize value for the attributes in the parent class, then it start assign value for its attributes. Let’s create couple of classes to participate in examples − Let’s take a closure look into the inheritance example −

In object-oriented terminology when class X extend class Y, then Y is called super/parent/base class and X is called subclass/child/derived class. Later you can add you own methods and data fields, thus inheritance provides a way to organize code, rather than rewriting it from scratch. Using inheritance you can use or inherit all the data fields and methods available in your base class.

It allows programmer to write better code.

Inheritance allows programmer to create a general or a base class first and then later extend it to more specialized class. Inheritance is one of the mechanisms to achieve the same. One of the major advantages of Object Oriented Programming is re-use. You must understand it better if you want to learn. Inheritance and polymorphism – this is a very important concept in Python.
