The Abstract base classes (ABC) is a base class which provides an interface to a number of derived classes. To make it more clear, let us consider an example. Let’s say that we have two classes A and B. The class A has a method print(), but the class B doesn’t have any method named print().
We have already learned python programming and we know how it works and how to code python. Now it’s the time to learn about python design pattern and the abstract base class.
What is the Abstract base class?
The abstract base class is a class that contains only the abstract method. All classes that are derived from the abstract base class must implement the abstract methods. The abstract base class is the parent class of the concrete classes.
Python Abstract Base Classes
Abstract base classes are very useful when we are designing a software application. They are mostly used to avoid code duplication and to improve performance.
The abstract base class is the parent of all classes, which means that all classes inherit the features and properties of the abstract base class. It provides the skeleton of the object, which contains all the basic data and the functions required by the application. It is also the most important class of Python programming language.
What is Abstract Base Class?
Abstract Base Class (ABC) is a base class, which contains only the common properties and methods. It cannot be instantiated, because it has no body. The classes that inherit this class will have the same properties and methods. These classes are called concrete child classes. All classes that inherit from ABC are called abstract child classes.
How it works?
Abstract base class is the parent class of all classes. Every class that inherits this class is called abstract child class. The classes that inherit this class are called concrete child classes.
Now the question arises, how does this class work? When a child class inherits an abstract base class, the child class automatically gets all the properties and methods of the abstract base class.
It can be said that all the properties and methods of the parent class will be inherited by the child class. This inheritance property of the class is known as meta-class.
Meta-Class:
Inheritance is one of the most essential concepts in object-oriented programming. When a child class inherits a parent class, then it is known as inheritance. Meta-Class is also an inheritance concept, which is used to create a virtual inheritance.
Virtual Inheritance:
In virtual inheritance, we have two types of inheritance:
- Single inheritance: Single inheritance is used to inherit a class from its direct ancestor. For example, in a tree structure, when a node inherits from its parent, it inherits all the properties and methods of the parent.
- Multiple inheritance: Multiple inheritance is used to inherit a class from several ancestors. It is also used to inherit multiple classes from a single ancestor. For example, a class can inherit from two different parents.
Single inheritance is used to inherit a class from its direct ancestor. For example, in a tree structure, when a node inherits from its parent, it inherits all the properties and methods of the parent.
Multiple inheritance is used to inherit a class from several ancestors. It is also used to inherit multiple classes from a single ancestor. For example, a class can inherit from two different parents.
Example:
We have a class named ‘Person’, which is inherited from the classes ‘Animal’ and ‘Human’. This class is also inherited from the meta-class.
Meta-Class:
Inheritance is one of the most important concepts in object oriented programming. When a child class inherits a parent class, then it is known as inheritance. Meta-Class is also an inheritance concept, which is used to create a virtual inheritance.
Why are ABCs necessary?
An abstract class is a superclass, which is not instantiable. Its main purpose is to provide a skeleton for the classes. It contains common properties and methods. Every class that inherits this class will have the same properties and methods.
Abstract base classes are mainly used to avoid code duplication. It is also useful when you want to override the behavior of a method or a property. It is the best option to avoid the code duplication and make the code better organized.
Why are ABCs important?
ABCs are also very helpful for performance improvement. If we are using a class as a parent then the objects of this class will take more time to instantiate. But if we are using ABC, then the time to instantiate the object will be reduced.
ABCs can be used to design the classes, which are difficult to implement. If you have a class that contains more than 50 functions or more than 20 properties, then it is better to use ABC.
import inspect
class MyABC(type):
def init (class_object, *args):
#print('Meta. init ')
#print(class_object)
#print(args)
# ('Base',
# (<type 'object'>,),
# {
# ' required_methods ': ['foo', 'bar'],
# ' module ': ' main ',
# ' metaclass ': <class ' main .MyABC'>
# })
#attr = dict(args)
if not ' metaclass ' in args[2]:
return
if not ' required_methods ' in args[2]:
raise Exception("No required_methods ")
name = args[0]
required_methods = set(args[2] [' required_methods '])
def my_init(self, *args, **kwargs):
if self. class . name == name:
raise Exception("You are required to subclass the '{}' class"
.format(name))
#print("my_init")
methods = set([ x[0] for x in
inspect.getmembers(self. class , predicate=inspect.ismethod)])
if not required_methods.issubset( methods ):
missing = required_methods - methods
raise Exception("Requried method '{}' is not implemented in '{}'"
.format(', '.join(missing), self. class . name ))
class_object. init = my_init
class Base(object):
metaclass = MyABC
required_methods = ['foo', 'bar']
# b = Base() # Exception: You are required to subclass the 'Base' class
class Real(Base):
def foo():
pass
def bar():
pass
r = Real()
class Fake(Base):
def foo():
pass
#f = Fake() # Exception: Requried method 'bar' is not implemented in class 'Fake'
class UnFake(Fake):
def bar():
pass
uf = UnFake()
Conclusion:
In conclusion, we have learned that what is an abstract base classes and why it is used in the programming languages. We have also seen how the abstract base class helps to avoid code duplication and to increase the performance of the software.