Python Glossary Русский

all Python 3abcterm

abc.ABCMeta

abstract classes

The metaclass for defining abstract base classes; ABC is a convenience wrapper.

Syntax

class C(metaclass=abc.ABCMeta): ...

You touch the metaclass directly when subclassing ABC is not an option — typically the class already has its own metaclass, which you then derive from ABCMeta. The other reason is register(): it declares an unrelated class a virtual subclass, so isinstance and issubclass start saying True, yet nothing is inherited and its abstract methods are never enforced.

Examples

import abc
print(type(abc.ABC) is abc.ABCMeta)   # → True
import abc
class Shape(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def area(self): return 0
print(type(Shape) is abc.ABCMeta)     # → True
print(Shape.__abstractmethods__)      # → frozenset({'area'})
class Circle(Shape): area = lambda self: 3.14
print(Circle().area())                # → 3.14
print(Shape())                        # → TypeError

See also

Open in the full glossarydocs.python.orgReport an inaccuracy