all Python 3OOPterm
Abstract classes
ABC
abc.ABC and @abstractmethod forbid creating instances of a class until every abstract method is implemented.
Syntax
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): ...
@abstractmethod blocks instantiation only when the class truly inherits from ABC (or sets metaclass=ABCMeta) — the decorator alone enforces nothing. The TypeError fires when you try to construct an instance, not when the class is defined.
Examples
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> float:
pass
@abstractmethod
def perimeter(self) -> float:
pass
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
import math
return math.pi * self.r**2
def perimeter(self):
import math
return 2 * math.pi * self.r
print(round(Circle(5).area(), 2)) # → 78.54
# TypeError при попытке создать экземпляр ABC
try:
Shape()
except TypeError as e:
print(e) # → Can't instantiate abstract class Shape...
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def speak(self) -> str:
pass
def describe(self):
return f'I say: {self.speak()}'
class Dog(Animal):
def speak(self):
return 'Woof!'
print(Dog().describe()) # → I say: Woof!
# Абстрактное свойство
class Base(ABC):
@property
@abstractmethod
def name(self) -> str:
pass
class Concrete(Base):
@property
def name(self):
return 'Concrete'
print(Concrete().name) # → Concrete
# ABCMeta без ABC
from abc import ABCMeta
class Interface(metaclass=ABCMeta):
@abstractmethod
def process(self): pass
class Impl(Interface):
def process(self): return 'done'
print(Impl().process()) # → done
# isinstance с ABC
print(isinstance(Dog(), Animal)) # → True
print(issubclass(Dog, Animal)) # → True
See also
Open in the full glossarydocs.python.orgReport an inaccuracy