Movatterモバイル変換


[0]ホーム

URL:


Python Training by Dan Bader

— FREE Email Series —

🐍 Python Tricks 💌

Whoa!!
Latest Python Tutorials:

Browse All Tutorials »

Abstract Base Classes in Python

By Dan Bader — Get free updates of new postshere.

Abstract Base Classes (ABCs) ensure that derived classes implement particular methods from the base class. In this tutorial you’ll learn about the benefits of abstract base classes and how to define them with Python’s built-in abc module.

What the ABC?

So what are Abstract Base Classes good for? A while ago I had a discussion at work about which pattern to use for implementing a maintainable class hierarchy in Python. More specifically, the goal was to define a simple class hierarchy for a service backend in the most programmer-friendly and maintainable way.

We had aBaseService class that defined a common interface and several concrete implementations. The concrete implementations do different things but all of them provide the same interface (MockService,RealService, and so on). To make this relationship explicit, the concrete implementations all subclassBaseService.

To make this code as maintainable and programmer-friendly as possible we wanted to make sure that:

  • instantiating the base class is impossible; and
  • forgetting to implement interface methods in one of the subclasses raises an error as early as possible.

When to Use Python’sabc Module

Now why would you want to use Python’sabc module to solve this problem? The above design is pretty common in more complex systems. To enforce that a derived class implements a number of methods from the base class, something like this Python idiom is typically used:

classBase:deffoo(self):raiseNotImplementedError()defbar(self):raiseNotImplementedError()classConcrete(Base):deffoo(self):return'foo() called'# Oh no, we forgot to override bar()...# def bar(self):#     return "bar() called"

So, what do we get from this first attempt at solving the problem? Calling methods on an instance ofBase correctly raisesNotImplementedError exceptions:

>>>b=Base()>>>b.foo()NotImplementedError

Furthermore, instantiating and usingConcrete works as expected. And, if we call an unimplemented method likebar() on it, this also raises an exception:

>>>c=Concrete()>>>c.foo()'foo() called'>>>c.bar()NotImplementedError

This first implementation is decent, but it isn’t perfect yet. The downsides here are that we can still:

  • instantiateBase just fine without getting an error; and
  • provide incomplete subclasses—instantiatingConcrete will not raise an error until we call the missing methodbar().

With Python’sabc module that wasadded in Python 2.6, we can do better and solve these remaining issues. Here’s an updated implementation using an Abstract Base Class defined with theabc module:

fromabcimportABCMeta,abstractmethodclassBase(metaclass=ABCMeta):@abstractmethoddeffoo(self):pass@abstractmethoddefbar(self):passclassConcrete(Base):deffoo(self):pass# We forget to declare bar() again...

This still behaves as expected and creates the correct class hierarchy:

assertissubclass(Concrete,Base)

Yet, we do get another very useful benefit here. Subclasses ofBase raise aTypeErrorat instantiation time whenever we forget to implement any abstract methods. The raised exception tells us which method or methods we’re missing:

>>>c=Concrete()TypeError:"Can't instantiate abstract class Concrete\with abstract methods bar"

Withoutabc, we’d only get aNotImplementedError if a missing method was actually called. Being notified about missing methods at instantiation time is a great advantage. It makes it more difficult to write invalid subclasses. This might not be a big deal if you’re writing new code, but a few weeks or months down the line, I promise it’ll be helpful.

This pattern is not a full replacement for compile-time type checking, of course. However, I found it often makes my class hierarchies more robust and more readily maintainable. Using ABCs states the programmer’s intent clearly and thus makes the code more communicative. I’d encourage you to read theabc module documentation and to keep an eye out for situations where applying this pattern makes sense.

ABCs in Python – Key Takeaways

  • Abstract Base Classes (ABCs) ensure that derived classes implement particular methods from the base class at instantiation time.
  • Using ABCs can help avoid bugs and make class hierarchies easier to maintain.

Object-Oriented Programming in Python: The 7 Best Resources (A Free PDF Cheat Sheet)

There are so many ways to learn about Object-Oriented Programming with Python. But only a few of them are actually useful. This (totally free) cheat sheet will point you tothe tutorials, videos, and books I found the most valuable to learn more about OOP with Python.

Python OOP Cheat Sheet
x
<strong>Object-Oriented Programming in Python</strong>:<em>The 7 Best Learning Resources</em>

Object-Oriented Programming in Python:The 7 Best Learning Resources

Free cheatsheet—just enter your email address below:

This article was filed under:oop,programming, andpython.

Related Articles:
Latest Articles:
← Browse All Articles

[8]ページ先頭

©2009-2025 Movatter.jp