Key Takeaways
Give a class only when its data and behavior belong together
A class earns its place. In this book, an object combines data with the actions that use or change that data. A point can hold coordinates and calculate its distance from another point. By contrast, a one-off calculation on a short list of coordinates may be clearer as a function. Python makes it easy to create classes, but ease is not a reason to add them: a class is useful when it makes a growing set of related operations easier to understand and reuse.
Make state explicit. In Python, ` init ` initializes an instance, and methods receive that instance through the conventional `self` parameter. Keep related modules organized, document public behavior with docstrings, and use explicit imports so readers can trace where names come from.
What's valuable here is the emphasis on cohesion rather than ceremony. A class is not a badge of sophistication; it is a boundary that gathers state and the operations that make sense for that state. This resembles the broader idea of information locality: readers should find the rules for a piece of data near the data itself. The boundary has a cost, though. If a class merely renames a tuple without clarifying behavior or responsibility, it adds indirection instead of understanding.
Design the public interface first, then hide what can safely change
Expose the useful controls. An object's public interface is the set of methods and attributes other objects use to work with it. The book compares this to a television remote: viewers need controls such as volume, not knowledge of the circuitry inside. Good abstraction means showing the details needed for a task while leaving irrelevant machinery out of view. A mechanic needs a different level of access from a driver, even when both work with the same car.
Protect stable agreements. Internal implementation can change without disturbing callers, but a changed method name or argument can break them. In Python, a leading underscore signals that an attribute is intended for internal use; it does not enforce secrecy. Double underscores mangle names, but do not provide security. UML diagrams can help teams discuss these relationships without turning every design conversation into a formal specification.
An interface functions like a contract between parts of a system. The idea connects object design to the management of complexity: each component should reveal enough to be useful, but not so much that every client depends on its internal construction. That reduces the number of changes that ripple through a codebase. The caution is that hiding details is not automatically good. An abstraction that conceals important constraints can make behavior harder to predict, so simplicity must include clear expectations, not just fewer visible methods.
Reach for composition before inheritance, and use duck typing when behavior is enough
Choose relationships carefully. Composition means building one object from other objects that form part of it. Inheritance expresses an is-a relationship, such as a rook being a chess piece. It can share behavior, but becomes fragile when used merely to avoid repeating a few lines. In the library-catalog example, separate author, actor, and artist subclasses created an awkward hierarchy. Modeling a contributor and a separate contribution role handled the same problem more flexibly.
Require the needed behavior. Python's duck typing lets code accept an object because it supports the operations being used, not because it inherits from a particular parent. A media player that calls `play()` can work with an unfamiliar audio class that provides that method. Abstract base classes can make such expectations explicit, especially for plugin APIs, but they should not be added automatically.
This is a practical version of a wider design principle: favor relationships that describe how components cooperate over taxonomies that try to classify everything. Composition keeps responsibilities separable, while duck typing makes extension possible without forcing distant classes into one family. The important qualification is that a matching method name is not enough. Two objects can both offer play() while behaving incompatibly. A dependable interface needs semantic expectations, not merely a list of methods.
Let Python's built-ins and first-class functions work before adding more classes
Use the language's shortcuts. Python's lists, dictionaries, sets, functions, and built-in operations already provide much of the flexibility that elaborate object hierarchies try to create. Functions are objects and can be passed as callbacks, while a ` call ` method lets an object act like a function. A menu can map choices directly to methods. A strategy, such as choosing how to fit an image to a screen, can often be represented by a function rather than a class containing only one method.
Add behavior when needed. Ordinary attributes are a sensible default. A property is useful when reading or setting an attribute needs extra behavior, such as validation, calculation, or caching, while preserving attribute-style access. A `with` statement uses a context manager to run setup and cleanup reliably, as when closing files. These tools show that Python can support object-oriented design without making every operation a class.
The book's strongest language-specific lesson is that object-oriented thinking does not require object-shaped syntax everywhere. Functions and built-ins can preserve the core design benefits with less scaffolding. This is a useful counterweight to programming cultures that equate abstraction with class count. At the same time, compact syntax can conceal complexity. A long comprehension or callback chain may be harder to maintain than a plainly named method, so idiomatic code still has to be judged by the reader's ability to follow it.
Choose containers by the questions your program needs to answer
Let the data structure express intent. Use a list when order and change matter, a set when uniqueness or membership matters, and a dictionary when one value must be found from a key. The book's song-library example collects artists in a set so repeated performers appear only once. Set operations then reveal which artists two libraries share. A dictionary is better for looking up a stock price by symbol.
Make data readable. Tuples bundle a fixed group of values, but numeric positions can hide what those values mean. A named tuple adds readable field names when the data is known and does not need to change. A regular dictionary suits changing or uncertain fields. Queues encode access rules: FIFO serves items in arrival order, LIFO returns the newest item first, and a priority queue returns the highest-priority item.
A container is more than storage; it declares which operations should be natural and which constraints matter. Choosing a set makes duplicates irrelevant by construction, while choosing a queue prevents clients from treating a waiting line as a random-access collection. That can make invalid states harder to express. The tradeoff is that a data structure's convenience can obscure performance limits. The book's contrast between list membership and set membership is a reminder to consider both meaning and scale.
Raise meaningful exceptions at boundaries, and always clean up resources
Make failure informative. An exception carries a problem up the call stack until code reaches a place that can respond sensibly. Catch specific exceptions when different failures require different responses; a bad password and an unknown username should not be confused. Custom exceptions let an API communicate domain-specific situations, such as an invalid withdrawal. The book also uses an out-of-stock exception to signal a normal business branch, rather than inventing ambiguous return values.
Keep cleanup reliable. A `finally` block runs whether an operation succeeds or raises, making it useful for releasing files, connections, or locks. The `else` clause runs when the `try` block completes without an exception. Avoid a bare catch-all unless every kind of failure, including interruption or program exit, truly belongs there. Often, checking for a problem before acting is less robust than attempting the operation and handling the specific exception.
Exceptions are a communication mechanism, not merely a crash report. They let a low-level operation describe what happened without dictating how every caller must respond, which is especially useful in libraries and layered systems. The book's out-of-stock example shows that exceptional control flow can represent an ordinary domain outcome. The design still needs restraint: exceptions should mark meaningful branches, not replace every conditional. If normal execution is dominated by exceptions, the interface may be making routine behavior unnecessarily opaque.
Treat text, bytes, and serialized data as different contracts
Know what a string represents. Python 3 strings are Unicode text; bytes are raw values used for storage and communication. Converting between them requires an encoding, and decoding with the wrong one can turn the same byte sequence into different characters. `bytearray` is the mutable option when bytes need to be assembled or changed. Regular expressions can recognize text patterns, but their compact syntax becomes difficult to read as patterns grow.
Choose a format for its audience. Pickle can preserve Python objects, but it is Python-specific and unsafe to load from an untrusted source. JSON is more portable because it represents data rather than executable behavior, though custom objects need conversion to and from simple values. The book's web-page example also shows how a temporary timer must be omitted from saved state and recreated when the object is restored.
Serialization is a boundary problem: an in-memory object must become a representation another process, program, or future version can interpret. The distinction between data and behavior matters because a format that works inside one Python program may be meaningless or dangerous elsewhere. This connects software design to protocol design, where compatibility depends on explicit agreements about representation. The practical challenge is version change. Even a safe, readable format still needs a plan for missing fields and evolving schemas.
Use design patterns as sketches, then simplify them for Python
Recognize recurring structures. A design pattern names a reusable arrangement of collaborating objects. A decorator adds optional behavior while preserving an object's interface; an observer separates a changing object from the actions triggered by its changes; a facade gives a simple entry point to a complicated subsystem. The strategy pattern swaps one algorithm for another, while the state pattern models an object whose behavior changes as it moves through states.
Adapt, do not imitate. Python functions can replace many single-purpose strategy or command classes. Composition can add optional behavior without multiple inheritance, and module-level objects often provide the practical convenience people seek from a singleton. The book treats flyweight as a specialized memory-saving technique, not a default design. Patterns are useful vocabulary for discussing a problem, not instructions to reproduce a canonical class diagram.
Patterns are most valuable as compressed explanations. Saying that a component behaves like an observer or facade helps a team discuss responsibilities without redrawing the whole design each time. Python's flexible functions and modules often remove the boilerplate found in traditional examples, which keeps the idea while simplifying its form. The danger is pattern spotting without problem solving: once a pattern becomes a goal, code can acquire extra layers that serve the diagram rather than the application.
Write tests to shape the API, not merely certify finished code
Test the behavior you intend. Test-driven development starts with a failing test, then adds code to pass it, and repeats. In the book's Vigenère-cipher example, tests for spaces, lowercase input, and individual characters expose requirements before the encoder is complete. Tests also force decisions about how a class is constructed and called, so they can improve the design rather than simply inspect it afterward.
Use coverage with judgment. Python's `unittest` and `pytest` can automate checks, while mocks replace expensive or external dependencies at a boundary. Code coverage shows which lines ran, not whether the tests checked the important outcomes. The cipher example reaches full line coverage yet still leaves some inputs undefined. Independent tests and explicit edge cases matter more than an impressive percentage.
A test is an executable example of how a client expects an interface to behave. Writing one first makes awkward construction or hidden dependencies visible before they spread through the implementation. This is especially powerful in dynamic languages, where many errors emerge only when particular values travel through the system. Tests can nevertheless create false confidence. High coverage measures execution, not adequacy, so useful suites must probe alternatives, boundaries, and failure paths rather than merely touch every line.
Match concurrency to the bottleneck, and keep shared state small
Choose by workload. Threads can overlap waiting on network or other input and output, but Python's global interpreter lock prevents ordinary Python threads from doing CPU calculations in parallel in the reference implementation described here. Multiprocessing can use multiple cores for CPU-heavy work, but passing data between processes costs time because objects must be serialized. Futures provide a clearer interface for submitting work and collecting results.
Use asynchronous I/O deliberately. AsyncIO uses coroutines and an event loop to coordinate many tasks that spend time waiting on network operations. Its code must yield control rather than block the loop. The book's image-compression test found that a process pool took about 7.5 seconds and a thread pool about 9 seconds on one large image, with data-transfer costs limiting the gain. Measure the actual workload before choosing.
Concurrency is a systems tradeoff, not a speed switch. The image-compression example is valuable because it measures a case where parallel work helps only modestly: moving large inputs between processes consumes much of the benefit. The distinction between waiting and calculating gives a useful first diagnosis, while futures and asynchronous I/O help make task boundaries visible. A further discipline is to minimize shared mutable state. That reduces coordination bugs, though it does not eliminate the need to handle failures and resource limits.
Analysis
This book is best understood as an applied introduction to object-oriented design through Python, not as a manifesto for class-centered programming. Its recurring question is practical: what representation makes a program easier to extend, test, and read? The answer changes with the problem. Sometimes it is a class with state and behavior; sometimes a built-in container, a function, or a generator is the cleaner abstraction. That flexibility is the book's defining strength.
The narrative moves from modeling objects and relationships to implementing them, then widens into Python's collections, iterators, patterns, testing, and concurrency. The case studies make the progression concrete. A library catalog reveals that inheritance can fail where composition and an explicit contribution role succeed. A link collector demonstrates sets and queues as design tools. The cipher example shows tests discovering requirements. Image compression turns concurrency from an abstract menu into a measured tradeoff.
The book's most durable lesson is restraint. Public interfaces should stay small, inheritance should express genuine substitutability, and patterns should be adapted to Python rather than copied ceremonially. Its advice also helps explain why object-oriented and functional techniques coexist: each is a way to organize responsibility, not a competing identity for the programmer.
Some material reflects the Python 3.4 era, especially the concurrency APIs and examples, so readers should verify current library details before reusing code. That age does not erase the design reasoning. In fact, the book is strongest when it teaches how to reason about boundaries, not when it catalogs syntax. Its limitations are also instructive: examples sometimes omit validation or production concerns to foreground one concept, and beginners should treat those samples as design demonstrations rather than finished software. The result is a useful guide to making Python abstractions deliberate, proportionate, and testable.
Review Summary
Python 3 Object-oriented Programming receives generally positive reviews for its clear explanations of OOP concepts in Python. Readers appreciate its practical examples, design pattern coverage, and suitability for both beginners and experienced programmers. The book is praised for its engaging writing style and comprehensive content. Some reviewers note that certain examples may be outdated, and a few find the case studies abstract. Overall, it's recommended for those looking to improve their Python OOP skills, with many readers finding it valuable for understanding complex concepts and improving code structure.
People Also Read
Glossary
Duck typing
Behavior-based compatibilityA way of accepting objects based on the operations they provide, rather than requiring them to inherit from a particular class. If a component needs an object with a play method, any object that supplies compatible behavior may work. The calling code should still rely on meaningful behavior, not merely matching method names.
Composition
Objects built from partsA relationship in which one object contains or coordinates other objects as components. A chess set, for example, can be modeled as containing a board and pieces, while the board contains positions. Composition is useful when a part belongs to a larger object or when responsibilities should be combined without claiming that one class is a subtype of another.
Mixin
Reusable added behaviorA class intended mainly to contribute a focused behavior to another class through inheritance, rather than to be used independently. A mail-sending mixin can add a send_mail method to a contact class. Mixins are most straightforward when they provide behavior distinct from the other parent classes and do not create conflicting method or initialization requirements.
Abstract base class
Declared behavioral requirementsA class that specifies methods or properties a concrete implementation is expected to provide. Python's abstract base class machinery can prevent instantiation while required methods remain unimplemented, or recognize classes that supply a specified protocol. It can document expectations for plugin systems, although ordinary duck typing often avoids the need to create a new abstract base class.
Property
Attribute with managed accessA Python attribute interface that can run custom behavior when a value is retrieved, assigned, or deleted. Properties let a class begin with straightforward attribute access and later add validation, calculation, or caching without requiring callers to switch to explicit getter and setter calls. The book recommends using ordinary attributes until such behavior is needed.
Context manager
Scoped setup and cleanupAn object that defines entry and exit behavior for use with Python's with statement. The entry method prepares a resource or returns an object for use inside the block. The exit method performs cleanup when the block finishes, including when an exception occurs. Files use this pattern to close reliably without a manually written cleanup path.
Generator
On-demand value producerAn object that produces a sequence of values one at a time, commonly created by a function containing yield. Each request resumes the function from its previous pause until another value is yielded or iteration ends. Generators avoid constructing an entire result collection in memory, which is valuable when processing large files or streams.
Coroutine
Value-consuming paused routineA routine that can pause at a yield point and receive data when execution resumes. In the Python model described in the book, a coroutine is created using generator syntax and can accept values through send. Unlike a generator used only to produce items, it can consume incoming values and preserve state between interactions.
Test-driven development
Tests guide implementationA development process that begins by writing a test for desired behavior, runs it to confirm that it fails, then implements code to pass it. The cycle repeats as requirements are added. Tests provide a safety net for changes and help clarify how an API should be used, although passing tests cannot prove that every relevant behavior has been tested.
Global interpreter lock
Python thread execution lockA lock in the reference Python implementation discussed in the book that prevents multiple threads from executing Python code on separate CPU cores at the same instant. Threads can still be useful when tasks wait on I/O, because the lock can be released while waiting. CPU-intensive parallel work may instead require multiple processes.
Flyweight pattern
Shared state saves memoryA memory optimization approach that stores common, relatively stable data once and lets many individual objects refer to it. For example, cars of the same model can share a model object describing standard features, while each car stores its own color and serial number. It adds complexity and is most appropriate when many similar objects create a real memory problem.
Download PDF
Download EPUB
.epub digital book format is ideal for reading ebooks on phones, tablets, and e-readers.