Monday, June 6, 2022

Interface in Python

Using interface you can specify what a class should do, but how class does it is not specified. So basically interface provides description of how an object should behave without actually providing that behavior implementation.

Interface in Python

An interface should just provide the method names without method bodies. Subclasses should provide implement for all the methods defined in an interface.

Unlike Java where a keyword ‘interface’ is provided for explicitly creating an interface in Python there is no such support for creating interfaces. If you are wondering why no such support in Python then you must know about "duck typing philosophy" of Python.

Python and duck typing

Python though strongly typed is also dynamically typed so the type of any object/field is implicitly assigned depending on where and how the field is used.

In Python focus is more on behavior of object rather than on its types. If you want to call a method on object there is no need to check the type of the object and there is no need to check whether that method really belongs to that object.

If there is an object that can fly and quack like a duck then it must be a duck, this is duck typing principle followed in Python. Let’s try to clarify it with an example-

class Duck:
  def sound(self):
    print('Quack Quack')

class Cat:
  def sound(self):
    print('Meow Meow')

class Human:
  def sound(self):
    print('Hey hello')

class Test:
  def invoke(self, obj):

t = Test()
obj = Duck()

obj = Cat()

obj = Human()


Quack Quack
Meow Meow
Hey hello

When the object of type Cat is passed to the invoke() method and sound() method is called using that object, sound() method of class Cat is executed. When object of type Duck is passed to the invoke() method and sound() method is called using that object, sound() method of class Duck is executed and same for object of type Human.

Those coming from Java which is a strongly typed language where every variable must be declared with a data type, would appreciate this difference between these languages. In Java if you need run time polymorphism best way is to create an interface and have the classes implement it. Then use interface reference to hold the actual object reference at run time to get run time polymorphism. In Python being a dynamically typed language (as shown in the above example) you can say that you get the run time polymorphism inbuilt with in the language. That may be one of the reason to not have explicit interface keyword in Python to create an interface.

How to create interface in Python

You may have a requirement to create an API that should be followed by the developers for implementation, that is best served by creating an interface so now the question is how to create interface in Python?

In Python you can create an interface using abstract class. If you create an abstract class which contains only abstract methods that acts as an interface in Python.

Note that it is not possible to create an object of an interface. Subclasses have to implement all the abstract methods of an interface and objects of those subclasses can be created. Using interface gives that flexibility that each subclass can provide its own implementation of the interface methods.

Interface in Python example

An abstract class Payment is created which contains only abstract method payment (no concrete methods) to qualify as an interface.

Two classes CreditCardPayment and MobileWalletPayment implement the interface method as per their requirement. Based on the object correct payment method is invoked, using isinstance() method it is also checked whether both objects are of type Payment or not.

from abc import ABC, abstractmethod
class Payment(ABC):
  def payment(self, amount):

class CreditCardPayment(Payment):
  def payment(self, amount):
    print('Credit card payment of- ', amount)

class MobileWalletPayment(Payment):
  def payment(self, amount):
    print('Mobile wallet payment of- ', amount)

obj = CreditCardPayment()
print(isinstance(obj, Payment))
obj = MobileWalletPayment()
print(isinstance(obj, Payment))


Credit card payment of-  100
Mobile wallet payment of-  200

Abstract class Vs Interface in Python

As we have seen there is no explicit ‘interface’ keyword in Python for creating an interface. To create an interface in Python abstract class is used which has only abstract methods. Now the question is when to go for abstract class when for an interface.

In your design if you have a set of classes which share some common functionality and there is some functionality which varies then you can opt for an abstract class where you can have concrete methods for the common functionality shared by all the sub classes and abstract methods for functionality that varies giving sub classes a chance to implement those abstract methods as per their requirement.

If there are a set of classes that you want to relate in a class hierarchy even if how the functionality is implemented completely differs then you can go for an interface. That gives sub classes a chance to implement all the abstract methods as per their requirement.

That's all for this topic Interface in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page

Related Topics

  1. Multiple Inheritance in Python
  2. Method Overriding in Python
  3. Constructor in Python - __init__() function
  4. Name Mangling in Python
  5. self in Python

You may also like-

  1. Strings in Python With Method Examples
  2. Tuple in Python With Examples
  3. Variable Length Arguments (*args), Keyword Varargs (**kwargs) in Python
  4. Python Program to Display Armstrong Numbers
  5. How to Read Excel File in Java Using Apache POI
  6. Association, Aggregation And Composition in Java
  7. ConcurrentHashMap in Java With Examples
  8. Autowiring in Spring Using @Autowired and @Inject Annotations