What you'll see sometimes is the following:

class Abstract1:
    """Some description that tells you it's abstract,
    often listing the methods you're expected to supply."""

    def aMethod(self):
        raise NotImplementedError("Should have implemented this")

Because Python doesn't have (and doesn't need) a formal Interface contract, the Java-style distinction between abstraction and interface doesn't exist. If someone goes through the effort to define a formal interface, it will also be an abstract class. The only differences would be in the stated intent in the docstring.

And the difference between abstract and interface is a hairsplitting thing when you have duck typing.

Java uses interfaces because it doesn't have multiple inheritance.

Because Python has multiple inheritance, you may also see something like this

class SomeAbstraction:
    pass  # lots of stuff - but missing something

class Mixin1:
    def something(self):
        pass  # one implementation

class Mixin2:
    def something(self):
        pass  # another

class Concrete1(SomeAbstraction, Mixin1):
    pass

class Concrete2(SomeAbstraction, Mixin2):
    pass

This uses a kind of abstract superclass with mixins to create concrete subclasses that are disjoint.

Answer from S.Lott on Stack Overflow
🌐
Python
docs.python.org › 3 › library › abc.html
abc — Abstract Base Classes
Source code: Lib/abc.py This module provides the infrastructure for defining abstract base classes(ABCs) in Python, as outlined in PEP 3119; see the PEP for why this was added to Python. (See also ...
Top answer
1 of 8
693

What you'll see sometimes is the following:

class Abstract1:
    """Some description that tells you it's abstract,
    often listing the methods you're expected to supply."""

    def aMethod(self):
        raise NotImplementedError("Should have implemented this")

Because Python doesn't have (and doesn't need) a formal Interface contract, the Java-style distinction between abstraction and interface doesn't exist. If someone goes through the effort to define a formal interface, it will also be an abstract class. The only differences would be in the stated intent in the docstring.

And the difference between abstract and interface is a hairsplitting thing when you have duck typing.

Java uses interfaces because it doesn't have multiple inheritance.

Because Python has multiple inheritance, you may also see something like this

class SomeAbstraction:
    pass  # lots of stuff - but missing something

class Mixin1:
    def something(self):
        pass  # one implementation

class Mixin2:
    def something(self):
        pass  # another

class Concrete1(SomeAbstraction, Mixin1):
    pass

class Concrete2(SomeAbstraction, Mixin2):
    pass

This uses a kind of abstract superclass with mixins to create concrete subclasses that are disjoint.

2 of 8
231

What is the difference between abstract class and interface in Python?

An interface, for an object, is a set of methods and attributes on that object.

In Python, we can use an abstract base class to define and enforce an interface.

Using an Abstract Base Class

For example, say we want to use one of the abstract base classes from the collections module:

import collections
class MySet(collections.Set):
    pass

If we try to use it, we get an TypeError because the class we created does not support the expected behavior of sets:

>>> MySet()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class MySet with abstract methods
__contains__, __iter__, __len__

So we are required to implement at least __contains__, __iter__, and __len__. Let's use this implementation example from the documentation:

class ListBasedSet(collections.Set):
    """Alternate set implementation favoring space over speed
    and not requiring the set elements to be hashable. 
    """
    def __init__(self, iterable):
        self.elements = lst = []
        for value in iterable:
            if value not in lst:
                lst.append(value)
    def __iter__(self):
        return iter(self.elements)
    def __contains__(self, value):
        return value in self.elements
    def __len__(self):
        return len(self.elements)

s1 = ListBasedSet('abcdef')
s2 = ListBasedSet('defghi')
overlap = s1 & s2

Implementation: Creating an Abstract Base Class

We can create our own Abstract Base Class by setting the metaclass to abc.ABCMeta and using the abc.abstractmethod decorator on relevant methods. The metaclass will be add the decorated functions to the __abstractmethods__ attribute, preventing instantiation until those are defined.

import abc

For example, "effable" is defined as something that can be expressed in words. Say we wanted to define an abstract base class that is effable, in Python 2:

class Effable(object):
    __metaclass__ = abc.ABCMeta
    @abc.abstractmethod
    def __str__(self):
        raise NotImplementedError('users must define __str__ to use this base class')

Or in Python 3, with the slight change in metaclass declaration:

class Effable(object, metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def __str__(self):
        raise NotImplementedError('users must define __str__ to use this base class')

Now if we try to create an effable object without implementing the interface:

class MyEffable(Effable): 
    pass

and attempt to instantiate it:

>>> MyEffable()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class MyEffable with abstract methods __str__

We are told that we haven't finished the job.

Now if we comply by providing the expected interface:

class MyEffable(Effable): 
    def __str__(self):
        return 'expressable!'

we are then able to use the concrete version of the class derived from the abstract one:

>>> me = MyEffable()
>>> print(me)
expressable!

There are other things we could do with this, like register virtual subclasses that already implement these interfaces, but I think that is beyond the scope of this question. The other methods demonstrated here would have to adapt this method using the abc module to do so, however.

Conclusion

We have demonstrated that the creation of an Abstract Base Class defines interfaces for custom objects in Python.

🌐
Readthedocs
interface.readthedocs.io › en › latest › abc.html
interface vs. abc — interface 1.4.0 documentation
The Python standard library abc (Abstract Base Class) module is often used to define and verify interfaces.
🌐
Python
docs.python.org › 3 › library › collections.abc.html
collections.abc — Abstract Base Classes for Containers
Interfaces specify semantics and relationships between methods that cannot be inferred solely from the presence of specific method names. For example, knowing that a class supplies __getitem__, __len__, and __iter__ is insufficient for ...
🌐
Sinavski
sinavski.com › home › interfaces abc vs. protocols
Interfaces: abc vs. Protocols - Oleg Sinavski
August 1, 2021 - Python is somewhat different from other popular languages since there are no interfaces on a language level. However, there are several library implementations: ... from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def eat(self, ...
🌐
Real Python
realpython.com › python-interface
Implementing an Interface in Python – Real Python
February 21, 2024 - To enforce the subclass instantiation of abstract methods, you’ll utilize Python’s builtin ABCMeta from the abc module. Going back to your UpdatedInformalParserInterface interface, you created your own metaclass, ParserMeta, with the overridden dunder methods .__instancecheck__() and .__subclasscheck__().
🌐
Justin A. Ellis
jellis18.github.io › post › 2022-01-11-abc-vs-protocol
Abstract Base Classes and Protocols: What Are They? When To Use Them?? Lets Find Out! - Justin A. Ellis
January 11, 2022 - In Python there are two similar, yet different, concepts for defining something akin to an interface, or a contract describing what methods and attributes a class will contain. These are Abstract Base Classes (ABCs) and Protocols.
🌐
Medium
medium.com › @shashikantrbl123 › interfaces-and-abstract-classes-in-python-understanding-the-differences-3e5889a0746a
Interfaces and Abstract Classes in Python: Understanding the Differences | by Shashi Kant | Medium
April 10, 2023 - from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass · Now, any class that implements the Shape interface must provide an implementation of the area() method. To implement an interface in Python, we create a class that inherits from the interface’s abstract base class.
Find elsewhere
🌐
k0nze
k0nze.dev › posts › python-interfaces-abstract-classes
Python’s Abstract Base Classes (ABC) and Interfaces Explained (With Code Snippets) | k0nze
February 22, 2024 - Even though Python uses duck typing, ... of objects. Therefore the Python module abc (short for abstract base classes) provides base classes and decorators to implement abstract classes and interfaces...
🌐
Real Python
realpython.com › ref › glossary › abstract-base-class
abstract base class (ABC) | Python Glossary – Real Python
In Python, an abstract base class (ABC) is a class that can’t be instantiated on its own and is designed to be a blueprint for other classes, allowing you to define a common interface for a group of related classes.
🌐
YouTube
youtube.com › watch
Python Interfaces and Abstract Base Class (ABC): A Must-Know for Advanced Programmers - YouTube
Take your Python programming skills to the next level with this must-know topic: interfaces and abstract classes. Learn how to implement these important conc...
Published   February 22, 2024
🌐
Reddit
reddit.com › r/python › python interfaces: choose protocols over abc
r/Python on Reddit: Python Interfaces: Choose Protocols Over ABC
February 12, 2023 - If it does then whether or not you use the ABC or the protocol seems irrelevant, both assure you that the required methods exist where you have annotated that a particular object is either ABC or protocol.
🌐
GeeksforGeeks
geeksforgeeks.org › abstract-classes-in-python
Abstract Classes in Python - GeeksforGeeks
It defines methods that must be implemented by its subclasses, ensuring that the subclasses follow a consistent structure. ABCs allow you to define common interfaces that various subclasses can implement while enforcing a level of abstraction.
Published   December 13, 2024
🌐
GeeksforGeeks
geeksforgeeks.org › abstract-base-class-abc-in-python
Abstract Base Class (abc) in Python - GeeksforGeeks
August 29, 2020 - Python has a module called abc (abstract base class) that offers the necessary tools for crafting an abstract base class. First and foremost, you should understand the ABCMeta metaclass provided by the abstract base class.
🌐
Python Course
python-course.eu › oop › the-abc-of-abstract-base-classes.php
20. The 'ABC' of Abstract Base Classes | OOP | python-course.eu
from abc import ABC, abstractmethod class AbstractClassExample(ABC): def __init__(self, value): self.value = value super().__init__() @abstractmethod def do_something(self): pass
🌐
Python Module of the Week
pymotw.com › 2 › abc
abc – Abstract Base Classes - Python Module of the Week
Since ABCWithConcreteImplementation is an abstract base class, it isn’t possible to instantiate it to use it directly. Subclasses must provide an override for retrieve_values(), and in this case the concrete class massages the data before returning it at all. $ python abc_concrete_method.py base class reading data subclass sorting data ['line one', 'line three', 'line two']
🌐
DataCamp
datacamp.com › tutorial › python-abstract-classes
Python Abstract Classes: A Comprehensive Guide with Examples | DataCamp
January 22, 2025 - This feature enables developers to impose a uniform interface for properties that subclasses must declare in addition to methods. To guarantee that every subclass provides its implementation, abstract properties can be specified using the @property decorator in combination with @abstractmethod.
🌐
GitConnected
levelup.gitconnected.com › python-interfaces-choose-protocols-over-abc-3982e112342e
Python interfaces: abandon ABC and switch to Protocols | by Oleg Sinavski | Level Up Coding
January 19, 2023 - Python is somewhat different from other popular languages since there are no interfaces on a language level. But there are several library implementations. The abc package is probably the most popular:
🌐
Medium
medium.com › @pouyahallaj › introduction-1616b3a4a637
Python Protocols vs. ABCs: A Comprehensive Comparison of Interface Design | Medium
May 29, 2023 - ABCs help enforce this interface compatibility by allowing you to define abstract methods that must be implemented by subclasses. To define an ABC in Python, you can make use of the abc module: