Abstract Classes in Python - GeeksforGeeks
This article explains the @abstractmethod
decorator in Python, which is used in combination with the Abstract Base Classes (ABCs) module to define abstract methods within abstract classes.
Abstract methods are declarations without implementation in the abstract base class. This means that the method must be implemented in its concrete subclasses. The @abstractmethod
decorator is used to mark a method as an abstract method.
Abstract classes cannot be instantiated directly; they serve as blueprints for other classes to derive from. Abstract classes are defined using the abc.ABC
metaclass or by inheriting from abc.ABC
.
@abstractmethod
DecoratorThe @abstractmethod
decorator is used to define abstract methods in abstract classes. Abstract methods have no implementation in the abstract base class and must be implemented in its concrete subclasses.
from abc import ABC, abstractmethod
class MyABC(ABC):
@abstractmethod
def my_abstract_method(self):
pass
This code block defines an abstract class MyABC
with an abstract method my_abstract_method
. The @abstractmethod
decorator is used to mark my_abstract_method
as an abstract method. Abstract methods are declarations without implementation in the abstract base class, and they must be implemented in its concrete subclasses.
In this case, any subclass inheriting from MyABC
must provide an implementation for the my_abstract_method
. This code block is an example of how to define an abstract class and an abstract method using the @abstractmethod
decorator.
The @abstractmethod
decorator is used to define abstract methods in abstract classes. Abstract methods have no implementation in the abstract base class and must be implemented in its concrete subclasses. This code block demonstrates how to define an abstract method using the @abstractmethod
decorator.
In Python, abstract classes cannot be instantiated directly. They serve as blueprints for other classes to derive from. Abstract classes are defined using the abc.ABC
metaclass or by inheriting from abc.ABC
.
import abc
class Shape(abc.ABC):
@abc.abstractmethod
def area(self):
pass