Interface vs abstract
- Python course
- Intermediate
- Lesson 51/116
- 4 min
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.
Practice 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)).
Starter code
# Use ABC and Protocol togetherSample 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))Expected output
Meow True
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which statement is true?
- ABC requires inheritance, Protocol does not Correct answer
- ABC does not require inheritance, Protocol does
- Both require inheritance
- Neither requires inheritance
Explanation: ABC requires inheritance; Protocol works with structural conformance.
2 ABC inheritance line
from abc import ABC, abstractmethod
class Animal(____):
@abstractmethod
def sound(self):
pass
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
Explanation: ABC inheritance defines an abstract class.
3 Match the ABC and Protocol difference
| Term | Meaning |
|---|---|
ABC |
Inheritance required |
Protocol |
Structural conformance |
@abstractmethod |
ABC decorator |
@runtime_checkable |
Protocol decorator |