In the previous chapter, we discussed the concept of Abstract Class and Abstract Method. You must understand the abstract class and abstract method before going through this chapter on Interfaces in Python. For your convenience, we have added below the link to all the chapters of our Python tutorial series.
Link to all the chapters of Python: Learn Python
Interfaces in Python
While abstract classes have both traditional and abstract methods, the interfaces only have abstract methods. It also means that Interfaces are abstract classes containing only the abstract methods. There will be no body or definition for any method in the Interface.
In other programming languages like Java, we create interfaces using the keyword ‘interface’. However, in Python, we create interfaces also using the abstract classes.
from abc import *
class InterfaceClass(ABC):
@abstractmethod
def display():
pass
class ChildClass(InterfaceClass):
def display(s):
print("This is child class")
instance1 = ChildClass()
instance1.display()
Output:
This is child class
In the program above, the class ‘InterfaceClass’ is an interface as it only contains an abstract method, display().
Abstract Classes Vs Interfaces in Python
Now that we know the concept of abstract classes and interfaces in Python let us list the significant differences between them.
Abstract Class | Interface |
Python provides the concept of Abstract Class implicitly. | Python does not offer the concept of Interface implicitly, unlike other programming languages like Java, where you’d declare an interface using specific keywords. |
It contains abstract methods and regular methods. | It contains only abstract methods. |
Abstract Classes are faster since the PVM finds and executes their methods faster. | Interfaces are comparatively slower. |
We use an abstract class in cases where all the objects commonly share a feature. | Interfaces are used chiefly in cases where the features are different for different objects. |