What’s a good way to implement something similar to a Delphi/C# interface or abstract class in Python? A class that will force all its subclasses to implement a particular set of methods?
What’s a good way to implement something similar to a Delphi/C# interface or abstract
Share
The simplest way to do this is to use the abstract base class implementation that has been included in Python since version 2.7.
This lets you mark a base class as abstract by using the
abc.ABCMetametaclass. You may then mark methods and properties as abstract. When you instantiate a class with theABCMetametaclass (or any of its subclasses) an exception will be thrown if any abstract properties or methods remain undefined in the instance.e.g.
The check is done only when the class is instantiated because it is perfectly legitimate to have a subclass that only implements some of the abstract methods and is therefore itself an abstract class.