Python Interfaces

  • Set metaclass=abc.ABCMeta
  • Implement __subclasshook__ method
  • All methods and properties marked as @abc.abstractmethod
  • No attributes
  • No constructor, no code

Python Interface Example

import abc
from typing import List

class IMyQueue(metaclass=abc.ABCMeta):
@classmethod def __subclasshook__(cls, subclass: type) -> bool: if cls is IMyQueue: attrs: List[str] = ['size'] callables: List[str] = ['enqueue', 'dequeue', 'peek'] ret: bool = True for attr in attrs: ret = ret and (hasattr(subclass, attr) and isinstance(getattr(subclass, attr), property)) for call in callables: ret = ret and (hasattr(subclass, call) and callable(getattr(subclass, call))) return ret else: return NotImplemented
@property @abc.abstractmethod def size(self) -> int: raise NotImplementedError
@abc.abstractmethod def enqueue(self, o: object) -> None: raise NotImplementedError
@abc.abstractmethod def dequeue(self) -> object: raise NotImplementedError
@abc.abstractmethod def peek(self) -> object: raise NotImplementedError

Using a Python Interface

class WaitingList(IMyQueue):
@property def size(self) -> int: # code here
def enqueue(self, o: object) -> None: #code here
def dequeue(self) -> object: #code here
def peek(self) -> object: #code here

Interfaces are Types

wait: IMyQueue = WaitingList()
wait.enqueue(Person())
wait.dequeue()

We can call any methods
defined by the interface

Python uses duck typing,
but Mypy wants a type

Python Inheritance

  • Subclass inherits all state and behavior
  • Subclass has all attributes and methods of superclass
  • Subclass constructor can call super() constructor
  • Subclass can override superclass methods with new code
class Canine:
    def __init__(self) -> None:
        self._name = "Name"
def bark(self) -> None: # code here
class Dog(Canine): def __init__(self) -> None: self._owner = "Owner"
def pet(self) -> None: # code here
class GuideDog(Dog): def __init__(self) -> None: self._trainer = "Trainer"
def guide(self) -> None: # code here
Subclass has all Superclass behaviors
lassie: GuideDog = GuideDog()
lassie.bark()
lassie.pet()
lassie.guide()

Multiple Inheritance

Classes in Python can inherit from any number of classes or interfaces

It will have access to all superclass attributes and methods

Be aware of name collisions!