Sure, here are simple-term summaries of the five abstract base classes in Python:
Certainly! Abstract Base Classes (ABCs) in Python provide a way to define a common interface for a group of related classes. They allow you to specify a set of methods that must be implemented by any class that wants to be considered a subclass of the abstract base class. This helps to enforce certain behavior and ensure that classes adhere to a specific contract.
Python has several built-in abstract base classes, and the five you mentioned are among them. Let's explore each one in more detail:
Callable (abc.Callable):
Purpose: The Callable
abstract base class is used to define objects that can be called like functions.
Required Method: The __call__
method. It must be implemented to make the object callable.
Example:
from abc import ABC, abstractmethod
class MyCallable(ABC):
@abstractmethod
def __call__(self, *args, **kwargs):
pass
class MyFunction(MyCallable):
def __call__(self, x):
return x + 1
func = MyFunction()
result = func(5)
print(result) # Output: 6
Container (abc.Container):
Purpose: The Container
abstract base class is used to define objects that can check for the presence of elements.
Required Method: The __contains__
method. It must be implemented to check if an element exists in the container.
Example:
from abc import ABC, abstractmethod
class MyContainer(ABC):
@abstractmethod
def __contains__(self, item):
pass
class MyList(MyContainer):
def __init__(self, items):
self.items = items
def __contains__(self, item):
return item in self.items
my_list = MyList([1, 2, 3, 4, 5])
print(3 in my_list) # Output: True
print(6 in my_list) # Output: False
Hashable (abc.Hashable):
Purpose: The Hashable
abstract base class is used to define objects that can be used as keys in a dictionary or elements in a set.
Required Method: The __hash__
method. It must be implemented to return a unique hash value for the object.
Example:
from abc import ABC, abstractmethod
class MyHashable(ABC):
@abstractmethod
def __hash__(self):
pass
class Point(MyHashable):
def __init__(self, x, y):
self.x = x
self.y = y
def __hash__(self):
return hash((self.x, self.y))
point = Point(2, 3)
my_dict = {point: "value"}
print(my_dict) # Output: {<__main__.Point object at 0x...>: 'value'}
Iterable (abc.Iterable):
Purpose: The Iterable
abstract base class is used to define objects that can be iterated over using a loop.
Required Method: The __iter__
method. It must be implemented to return an iterator object.
Example:
from abc import ABC, abstractmethod
class MyIterable(ABC):
@abstractmethod
def __iter__(self):
pass
class MyList(MyIterable):
def __init__(self, items):
self.items = items
def __iter__(self):
return iter(self.items)
my_list = MyList([1, 2, 3, 4, 5])
for item in my_list:
print(item)
# Output:
# 1
# 2
# 3
# 4
# 5