Classes in Python: Insights from PyCon 2012

How do classes and their instances work in Python?

In Python, classes are basically a bunch of namespace tricks.

Why use classes?

Classes are useful “when you have … mutable data, and … related functions that you want to use with that data”. There are often better tools:

So classes are the optimal solution less often than you might think. Given this:

Though classes can also be useful for creating small namespaces, subclassing is for code re-use (“don’t repeat yourself”), not hierarchy creation. In other words, sometimes it’s natural to have Animal subclass Dog, not vice versa.

The standard library has a very flat namespace. — Jack Diederich

How to maximise code re-use using classes

Fundamentals: A subclass can do one or more of…

Substituability:

The ‘framework’ design pattern:

Take advantage of magic methods:

For example, a useful way to define a class’s __repr__: return self.__class__.__name__. That way instances of subclasses get the name of that subclass.

Other notes

References