Python Abstract Class Inheritance Example
Python comes with a module which provides the base for defining abstract base classesabc and that module name is abc.
Python abstract class inheritance example. Pass note that the type of abc is still abcmeta therefore inheriting from abc requires the usual precautions regarding metaclass usage as multiple inheritance may lead to metaclass conflicts. A concrete class which is a sub class of such abstract base class then implements the abstract base by overriding its abstract methods. Parent class is the class being inherited from also called base class. How abstract base classes work.
Inheritance is capability of an class to inherit all methods of base class from which it is derived and can add new features to the class without modifying it. This module is called for obvious reasons abc. We will define a class physicianrobot which inherits from robot. Abc works by marking methods of the base class as abstract.
In fact python on its own doesnt provide abstract classes. We will stick with our beloved robots or better robot class from the previous chapters of our python tutorial to show how the principle of inheritance works. This helps in representing the real world problem better and also reusability of code with data protection with features like encapsulation in simple language. The new class is called derived or child class and the one from which it inherits is called the base or parent class.
Inheritance allows us to define a class that inherits all the methods and properties from another class. It refers to defining a new class with little or no modification to an existing class. The employee class in the example above is what is called an abstract base class. Yet python comes with a module which provides the infrastructure for defining abstract base classes abcs.
From abc import abc class myabc abc. Inheritance is a powerful feature in object oriented programming. Child class is the class that inherits from another class also called derived class. Python provides the abc module to define abstract base classes.
The abc module in python library provides the infrastructure for defining custom abstract base classes. This is done by atabsttractmethod decorator. With this class an abstract base class can be created by simply deriving from abc avoiding sometimes confusing metaclass usage for example. By default python does not provide abstract classes.
Our example implemented a case of simple inheritance which has nothing to do with an abstract class. Abstract base classes exist to be inherited but never instantiated.