ABC's features and roles in python
ABC (Abstract Base Class) is a feature provided by Python for supporting abstraction and polymorphism in object-oriented programming. ABC is used to define abstract classes and specify methods that must be implemented by subclasses.
Definition of Abstract Classes:
ABC allows the definition of abstract classes. Abstract classes can contain one or more abstract methods and cannot be instantiated directly.
from abc import ABC, abstractmethod
class MyAbstractClass(ABC):
@abstractmethod
def my_abstract_method(self):
pass
Definition of Abstract Methods:
Abstract methods can be defined using the @abstractmethod decorator. Subclasses must implement these abstract methods.
Support for Polymorphism:
ABC supports polymorphism, allowing different classes to inherit from the same abstract class and provide a consistent interface by implementing the same methods.
class AnotherClass(ABC):
@abstractmethod
def my_abstract_method(self):
pass
Instance Checking and Enforcement:
The "isinstance" function can be used to check whether an object is an instance of a specific abstract class. This allows enforcing the desired interface in the code.
obj = MyConcreteClass()
if isinstance(obj, MyAbstractClass):
obj.my_abstract_method()
Self-Check and Enforcement:
ABC provides self-checking capabilities. If a subclass does not implement an abstract method, attempting to create an instance of that subclass will raise a TypeError.
class MyConcreteClass(MyAbstractClass):
pass # Raises TypeError since my_abstract_method is not implemented