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?
Asked
Active
Viewed 139 times
2
-
1Why not just make the base class with all the methods and just not overwrite them in the subclasses? – Volatility Jan 07 '13 at 11:35
-
1http://docs.python.org/2/library/abc.html Is this what you want ? – asheeshr Jan 07 '13 at 11:36
-
See also http://www.doughellmann.com/PyMOTW/abc/ for a good example of use – Duncan Jan 07 '13 at 11:37
-
Similar http://stackoverflow.com/questions/5856963/abstract-methods-in-python – asheeshr Jan 07 '13 at 11:38
-
1Also see [Pythonic use of the isinstance function?](http://programmers.stackexchange.com/questions/175277/175286#175286) – Martijn Pieters Jan 07 '13 at 11:43
-
Can I ask why you want to do this, rather than duck typing? – Benjamin Hodgson Jan 07 '13 at 12:01
-
1"Can I ask why you want to do this". No... LOL – Vector Jan 07 '13 at 23:57
1 Answers
5
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.ABCMeta
metaclass. You may then mark methods and properties as abstract. When you instantiate a class with the ABCMeta
metaclass (or any of its subclasses) an exception will be thrown if any abstract properties or methods remain undefined in the instance.
e.g.
>>> from abc import ABCMeta, abstractmethod
>>> class Foo(object):
__metaclass__ = ABCMeta
@abstractmethod
def bar(self): pass
>>> class BadFoo(Foo):
pass
>>> BadFoo()
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
BadFoo()
TypeError: Can't instantiate abstract class BadFoo with abstract methods bar
>>> class GoodFoo(Foo):
def bar(self):
return 42
>>> GoodFoo()
<__main__.GoodFoo object at 0x027354B0>
>>>
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.

Duncan
- 92,073
- 11
- 122
- 156