I have a number of classes which all share the same methods, only with different implementations. In Java, it would make sense to have each of these classes implement an interface or extend an abstract class. Does Python have anything similar to this, or should I be taking an alternative approach?
Share
There’s a bit of a story behind interfaces in Python. The original attitude, which held sway for many years, is that you don’t need them: Python works on the EAFP (easier to ask forgiveness than permission) principle. That is, instead of specifying that you accept an, I don’t know, ICloseable object, you simply try to
closethe object when you need to, and if it raises an exception then it raises an exception.So in this mentality you would just write your classes separately, and use them as you will. If one of them doesn’t conform to the requirements, your program will raise an exception; conversely, if you write another class with the right methods then it will just work, without your needing to specify that it implements your particular interface.
This works pretty well, but there are definite use cases for interfaces, especially with larger software projects. The final decision in Python was to provide the
abcmodule, which allows you to write abstract base classes i.e. classes that you can’t instantiate unless you override all their methods. It’s your decision as to whether you think using them is worth it.The PEP introducing ABCs explain much better than I can: