Israel Teneda

Israel Teneda

Python Interfaces

Since Python uses duck typing, interfaces are not necessary. The original attitude, which held sway for many years, is that you don't need them: Python works on the EAFP (easier to ask forgiveness than permission) principle.

This works pretty well, but there are definite use cases for interfaces, especially with larger software projects. The final decision in Python was to provide the abc module, which allows you to write abstract base classes.

import abc

class Piece(metaclass=abc.ABCMeta):
    def move(self, **kargs):
        raise NotImplementedError 

class Queen(Piece):
    def move(self, square):
        # Specific implementation for the Queen's movements

class King(Piece):

# Allows you to create an instance of the Queen class
queen = Queen()

# Does not allow you to create an instance of the King class, 
# because the abstract method move() is not implemented.
king = King()


Implementing an Interface in Python

How do I implement interfaces in python?

Java abstract/interface design in Python