metaclass=abc.ABCMeta
__subclasshook__
method@abc.abstractmethod
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
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
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
super()
constructorclass 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
lassie: GuideDog = GuideDog()
lassie.bark()
lassie.pet()
lassie.guide()
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!