Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between class abstractclass(metaclass=ABCMeta) and class abstractclass(ABC)

Tags:

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?

like image 951
user785099 Avatar asked Jul 29 '21 02:07

user785099


People also ask

What is the difference between ABC and ABCMeta?

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.

What is ABCMeta 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.

What is Python ABC package?

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.

What is a metaclass in Python?

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.


1 Answers

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__ = ()
like image 85
blhsing Avatar answered Sep 21 '22 19:09

blhsing