Python
Interface vs abstract
Learn the difference between abstract class and protocol.
Interface vs abstract
Python has no language-level distinction between “interface” and “abstract”. ABC enforces conformance through inheritance; Protocol works with structural conformance and does not require inheritance. Both impose the “have these methods” requirement differently.
ABC is strong and explicit: the subclass must inherit from ABC. Protocol is flexible: any class with the right methods is considered conforming. Which one you choose shows how strict the architecture is.
Which when?
If you want to enforce a shared interface, choose ABC: all subclasses descend from the same base. If you want a flexible “if it has these methods it is fine” approach, choose Protocol: outside classes also count as conforming.
Example: ABC fits when you build an animal hierarchy in your own library; Protocol fits when you design a general API where user classes should also conform. You can even mix them; the architectural need decides.
Exercise ABC and Protocol together
Start with from abc import ABC, abstractmethod and from typing import Protocol, runtime_checkable. Define the abstract class Animal(ABC); inside, use @abstractmethod with def sound(self): and pass. Define @runtime_checkable with class Speaker(Protocol):; inside, write def speak(self) -> str: .... Then define class Cat(Animal):; in the body write def sound(self): with return "Meow" and def speak(self) -> str: with return "meow". Finally create c = Cat() and print with print(c.sound(), isinstance(c, Speaker)).
Show example solution
# Use ABC and Protocol together
from abc import ABC, abstractmethod
from typing import Protocol, runtime_checkable
class Animal(ABC):
@abstractmethod
def sound(self):
pass
@runtime_checkable
class Speaker(Protocol):
def speak(self) -> str: ...
class Cat(Animal):
def sound(self):
return "Meow"
def speak(self) -> str:
return "meow"
c = Cat()
print(c.sound(), isinstance(c, Speaker))
Test yourself
-
Which statement is true?
- ABC requires inheritance, Protocol does not
- ABC does not require inheritance, Protocol does
- Both require inheritance
- Neither requires inheritance
Show answer
ABC requires inheritance, Protocol does not — ABC requires inheritance; Protocol works with structural conformance.
-
ABC inheritance line
from abc import ABC, abstractmethod
class Animal(____):
@abstractmethod
def sound(self):
pass
Show answer
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
-
Match the ABC and Protocol difference
- ABC
- Inheritance required
- Protocol
- Structural conformance
- @abstractmethod
- ABC decorator
- @runtime_checkable
- Protocol decorator
Next lesson: Summary - Abstract classes