python inheritance and polymorphism

Inheritance and Polymorphism in Python

Current Status
Not Enrolled
Price
PRO
Get Started

Inheritance

Inheritance is one of the most important concepts of object-oriented programming. It makes it possible to divide complex problem areas into meaningful class hierarchies. Properties and capabilities that several classes possess are implemented only once in a superclass and inherited by one or more subclasses.

Thus, not only is code reused, but the logic of these properties and capabilities can be changed for all inheriting classes in a single place without having to change the code of each individual inheriting class.

Python supports the concept of multiple inheritance. This means that a class can inherit from several base classes. In this case, each individual class is enumerated after the colon, separated by commas.

The inheriting classes are called superclasses or parent classes, while the inheriting classes are respectively called subclasses or child classes. The inheriting class extends the class from which it inherits, as it (usually) has properties and capabilities beyond those of the superclass.

Polymorphism

Polymorphism is another important concept in object-oriented programming. With the concept of polymorphism a function (e.g. print) or an operator (+, -, …) can be used with different data types.

Polymorphism is often used in inheritance, i.e. a variable can be assigned not only objects of the type of the class specified in the declaration, but also objects of the type of the child classes. This only works because each child class must also implement all methods and attributes of its parent classes.  This ensures that all child classes have the same methods as the parent class. However, the methods can be implemented differently, this is called “overwriting” the method.