Chapter 22. Designing with Classes

So far, we’ve concentrated on the OOP tool in Python—the class. But OOP is also about design issues—how to use classes to model useful objects. This section will touch on a few OOP core ideas, and look at some additional examples that are more realistic than the examples shown so far. Many of the design terms mentioned here require more explanation than we can provide; if this section sparks your curiosity, we suggest exploring a text on OOP design or design patterns as a next step.

Python and OOP

Python’s implementation of OOP can be summarized by three ideas:


Is based on attribute lookup in Python (in expressions).


In X.method, the meaning of method depends on the type (class) of X.


Methods and operators implement behavior; data hiding is a convention by default.

By now, you should have a good feel for what inheritance is all about in Python. We’ve talked about Python’s polymorphism a few times already; it flows from Python’s lack of type declarations. Because attributes are always resolved at runtime, objects that implement the same interfaces are interchangeable. Clients don’t need to know what sort of object is implementing a method they call.

Encapsulation means packaging in Python—hiding implementation details behind an object’s interface; it does not mean enforced privacy, as you’ll see in Chapter 23. Encapsulation allows the implementation of an object’s interface to be changed, without impacting the ...

Get Learning Python, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.