Interface in Python
An interface in Python is a general specification for implementing a specific service, declaring the required methods without specifying exactly how they must be implemented by any class that implements to it.
In other words, an interface is a blueprint for designing classes containing a specific set of methods that must be implemented bu any class implementing to it.
Implementing an interface is a systemic approach to writing an organized code and achieve abstraction. In interface, we do not provide implementation details because different classes might need to implement the defined methods in different ways.
For example, architect-level people in industry create interfaces, and then they are given to developers for writing classes by implementing interfaces provided.
Using interfaces is the best way to expose a project’s API to other projects or third-party vendors. By providing interfaces with defined methods, developers can offer a clear set of guidelines for implementing certain functionalities. This facilitates collaboration and integration between different systems or vendors, allowing for smoother interactions and interoperability.
For instance, consider HDFC Bank exposing certain methods or interfaces to various shopping carts. This approach facilitates seamless integration between the bank’s services and different shopping platforms.
Shopping carts can utilize the bank’s functionalities through these defined interface methods without requiring an in-depth understanding of the bank’s internal workings. This promotes efficiency and security in interactions between systems.
How to Define an Interface in Python
To define an interface in Python, we don’t use a specific keyword like ‘interface’ as in some other programming languages like Java. In Python, we can create or define an interface using an abstract class.
If we define an abstract class and contain only abstract methods (without providing their implementation details), then this abstract class will act as an interface in Python. Here’s an example to define an interface using an abstract class:
from abc import ABC, abstractmethod
# Define an abstract class inheriting from ABC
class MyInterface(ABC):
# Define abstract methods without implementation
@abstractmethod
def method1(self):
pass
@abstractmethod
def method2(self):
pass
In this code, we have created an interface named MyInterface using an abstract class that inherits from ABC class of abc module or package. Inside this abstract class, we have defined methods without implementations using the @abstractmethod decorator.
Once we defined an interface, we can create any number of separate classes by providing their own unique implementation for all the abstract methods defined by an interface.
A class that implements an interface is commonly known as implementation class. A class can implement any number of interfaces in Python. Every implementation class can have its own implementation for abstract methods specified in the interface, as shown in the below figure.
Since implementation classes provide concrete implementations for all the abstract methods specified in the interface, you can create instances of these implementation classes in Python.
Python Interface Example Programs
Let’s take some example program in which we will create an interface using an abstract class containing only abstract methods. The concrete classes will implement the interface with their own unique implementations.
Example 1:
from abc import ABC, abstractmethod
# Defining an interface using an Abstract Base Class (ABC)
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
# Implementing the interface for specific shapes
class Square(Shape):
def __init__(self, side_length):
self.side_length = side_length
def area(self):
return self.side_length ** 2
def perimeter(self):
return 4 * self.side_length
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
def perimeter(self):
return 2 * 3.14 * self.radius
# Creating instances of concrete subclasses that implement an interface named Shape.
square = Square(5)
circle = Circle(7)
# Calling methods of subclasses using object references and displaying the result.
print("Square Area:", square.area())
print("Square Perimeter:", square.perimeter())
print("Circle Area:", circle.area())
print("Circle Perimeter:", circle.perimeter())
Output:
Square Area: 25
Square Perimeter: 20
Circle Area: 153.86
Circle Perimeter: 43.96
In this example code, we have created an interface named Shape using an abstract class inheriting from ABC class. This interface contains two abstract methods: area() and perimeter(). The Square and Circle classes implement the Shape interface by providing concrete implementations for the abstract methods.
Then, we have created instances of Square and Circle that allow us to utilize the implemented interfaces to calculate the area and perimeter of these shapes. This demonstration shows how an interface can be created using an abstract base class in Python.
Example 2:
from abc import ABC, abstractmethod
# Defining the interface using an Abstract Base Class (ABC)
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
# Implementing the interface for specific animals
class Dog(Animal):
def make_sound(self):
return "Woof!"
class Cat(Animal):
def make_sound(self):
return "Meow!"
class Duck(Animal):
def make_sound(self):
return "Quack!"
# Creating instances of concrete classes that implement an interface Animal.
dog = Dog()
cat = Cat()
duck = Duck()
print("Dog says:", dog.make_sound())
print("Cat says:", cat.make_sound())
print("Duck says:", duck.make_sound())
Output:
Dog says: Woof!
Cat says: Meow!
Duck says: Quack!
Ways to Create Interface in Python
In Python, there are two ways to create and implement the interface. They are:
- Informal Interface
- Formal Interface
1. Informal Interface
An informal interface in Python also acts as a blueprint for creating a class with methods that can be overridden without strict enforcement. It allows for flexibility in method implementation, emphasizing the behavior of objects rather than imposing rigid guidelines. An informal interface is also known as duck typing.
Duck typing in Python is actually a programming concept that is mostly adopted in programming languages that supports dynamic typing, such as Python and JavaScript. The term “duck typing” comes from the following quote: “If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck”.
The meaning of this quote is that if a bird is behaving like a duck, it will probably be a duck. In duck typing, it is possible to identify an object by its behavior rather than the type of class of an object. In other words, the type of class of an object is less important rather than method (behavior) it defines.
Using duck typing, Python does not check the type of an object, but it executes the method that is expected. Hence, this approach emphasizes an object’s behavior over its specific type, promoting flexibility and code reusability. For example, consider the following below example:
Example 3:
class Duck:
def quack(self):
print("Quack!")
class Person:
def quack(self):
print("I'm quacking like a duck!")
def imitate_quack(obj):
obj.quack()
# Usage of the informal interface
duck = Duck()
person = Person()
imitate_quack(duck)
imitate_quack(person)
Output:
Quack!
I'm quacking like a duck!
This example code demonstrates the concept of duck typing in Python, where objects are checked based on their behavior rather than their specific type. In this code, we have defined a class named Duck, containing a quack() method that prints “Quack!” when called.
Then, we have defined another class named Person with a method quack() that prints “I’m quacking like a duck!” when called. After that, we have defined a function imitate_quack() that takes an object as an argument and calls its quack() method.
Outside the class definition, we have created an instance of the Duck class and Person class, respectively. The imitate_quack(duck) calls the imitate_quack() function with the duck object as an argument. Since the Duck class has a quack() method defined, it prints “Quack!” when executed.
The imitate_quack(person) calls the imitate_quack() function with the person object as an argument. Even though person is an instance of the Person class, which has its own quack() method. Therefore, it prints “I’m quacking like a duck!” because the imitate_quack() function relies on the presence of the quack() method rather than the specific class type.
2. Formal Interface
In contrast, we define a formal interface in Python through abstract base classes (ABCs), as we have done in the above examples 1 and 2.
ABCs acts as a form of interface or base class, defining abstract methods. When concrete classes inherit from these base classes, they’re obliged to implement all the methods defined in the base class. This enforces a contract, ensuring that derived classes provide specific functionalities.
We cannot directly instantiate interfaces or ABCs in Python. Instead, they are used as base classes to create objects. It’s through inheriting from these base classes that objects implement the interface’s methods.
We can use type() function that confirms whether an object implements a particular interface (in Python, an ABC). It checks if the object inherits from a specific class (interface/ABC) and thus indicates its adherence to that interface. Let us consider a simple example below:
Example 4:
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
square = Square(5)
print(square.area())
Output:
25
In this example, the Shape class acts as a formal interface with the area() method defined as an abstract method. The Square class implements this method, ensuring adherence to the interface.
Comparing Informal and Formal Interfaces
Informal interfaces, being more flexible, focus on the object’s behavior, while formal interfaces enforce explicit declarations. Choosing between the two depends on the project’s requirements and the desired level of control.
Advantages and Disadvantages
Informal interfaces offer flexibility and ease of implementation but may lack strictness, whereas formal interfaces ensure adherence to defined contracts but may require more upfront planning.
Frequently Asked Questions on Interface
Q1: Can a class in Python implement multiple interfaces?
Yes, Python supports multiple inheritance, so a class can implement multiple interfaces by inheriting from multiple abstract base classes.
Q2: What is the difference between an abstract base class and an interface?
An abstract base class can contain both abstract and concrete methods, while an interface only defines abstract methods that must be implemented by subclasses.
Q3: Is interface in Python similar to those in other programming languages like Java or C#?
Yes, the fundamental concept of an interface in Python is similar to that in other languages. However, Python uses abstract base classes to implement or achieve this feature.
Q4: Is it mandatory to use interfaces in Python?
No, it’s not mandatory, but using interfaces can greatly enhance the quality and maintainability of our code, especially in larger projects.
Q5: How can we check if a class implements an interface in Python?
We can use the isinstance() method to determine if an object is an instance of a class that implements to a specific interface.
In this tutorial, we have discussed the interface in Python with the help of some important example programs. Hope that you will have understood the basic concept of defining interface and practiced all example programs.
Thanks for reading!!!





