I have seen two ways for defining Abstract Classes in Python.
This one:
from abc import ABCMeta, abstractmethod
class AbstactClass(metaclass = ABCMeta):
And this one:
from abc import ABC, abstractmethod
class AbstractClass2(ABC):
What are there differences between them and what are the respective usage scenarios?
ABCMeta . i.e abc. ABC implicitly defines the metaclass for us. The only difference is that in the former case you need a simple inheritance and in the latter you need to specify the metaclass.
ABCMeta metaclass provides a method called register method that can be invoked by its instance. By using this register method, any abstract base class can become an ancestor of any arbitrary concrete class.
The 'abc' module in Python library provides the infrastructure for defining custom abstract base classes. 'abc' works by marking methods of the base class as abstract. This is done by @absttractmethod decorator.
A metaclass in Python is a class of a class that defines how a class behaves. A class is itself an instance of a metaclass. A class in Python defines how the instance of the class will behave. In order to understand metaclasses well, one needs to have prior experience working with Python classes.
There is no actual functional difference. The ABC
class is simply a convenience class to help make the code look less confusing to those who don't know the idea of a metaclass well, as the documentation states:
A helper class that has ABCMeta as its metaclass. With this class, an abstract base class can be created by simply deriving from ABC avoiding sometimes confusing metaclass usage
which is even clearer if you look at the the implementation of abc.py, which is nothing more than an empty class that specifies ABCMeta
as its metaclass, just so that its descendants can inherit the type:
class ABC(metaclass=ABCMeta):
"""Helper class that provides a standard way to create an ABC using
inheritance.
"""
__slots__ = ()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With