Sometimes you want a class that serves only as a template: it defines which methods its subclasses must have, but it makes no sense to create objects from it. That is an abstract class.
The problem
class Shape:
def area(self):
pass # what area does a "shape" in general have?
s = Shape() # Python allows it, although it makes no sense
print(s.area()) # None
Abstract classes with abc
The abc module (Abstract Base Classes) lets you prevent an object of the base class from being created and force subclasses to implement certain methods:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
s = Shape()
# TypeError: Can't instantiate abstract class Shape ... abstract method 'area'
You inherit from ABC and the mandatory methods are marked with @abstractmethod.
Implementing the abstract class
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self): # mandatory
return self.side ** 2
c = Square(4)
print(c.area()) # 16
If a subclass forgets to implement an abstract method, it cannot be instantiated either:
class Triangle(Shape):
pass
Triangle()
# TypeError: Can't instantiate abstract class Triangle ... abstract method 'area'
An abstract class can also have normal methods
class Animal(ABC):
def __init__(self, name):
self._name = name
def get_name(self): # concrete: already done
return self._name
@abstractmethod
def eat(self): # abstract: each subclass defines it
pass
class Cat(Animal):
def eat(self):
print("Eating fish")
It is what Abstract classes asks for: a base class with attributes and methods already solved, and one abstract method that each subclass implements.
Interfaces
An interface is a contract: a list of methods that a class promises to offer, without giving any detail on how. Python does not have the interface keyword like Java or C#. It is simulated with an abstract class that has only abstract methods:
class Flyer(ABC):
@abstractmethod
def fly(self):
pass
@abstractmethod
def land(self):
pass
class Bird(Flyer):
def fly(self):
print("Flapping")
def land(self):
print("On the branch")
And since Python allows multiple inheritance, a class can implement several interfaces at once: class Duck(Flyer, Swimmer):.
It is the structure of Interfaces: a class that implements the methods the interface demands.
Abstract class or interface?
| Abstract class | Interface (simulated) | |
|---|---|---|
| Methods | Abstract and concrete | Abstract only |
| Attributes | May have | Usually none |
| Use | Common base with part of the code already done | Contract about what can be done |