Start free trial
Trending New Genres Authors
EnglishEnglish
EspañolSpanish
简体中文Chinese
繁體中文Chinese (Traditional)
FrançaisFrench
DeutschGerman
日本語Japanese
PortuguêsPortuguese
ItalianoItalian
한국어Korean
РусскийRussian
NederlandsDutch
العربيةArabic
PolskiPolish
हिन्दीHindi
Tiếng ViệtVietnamese
SvenskaSwedish
ΕλληνικάGreek
TürkçeTurkish
ไทยThai
ČeštinaCzech
RomânăRomanian
MagyarHungarian
УкраїнськаUkrainian
IndonesiaIndonesian
DanskDanish
SuomiFinnish
БългарскиBulgarian
עבריתHebrew
NorskNorwegian
HrvatskiCroatian
CatalàCatalan
SlovenčinaSlovak
LietuviųLithuanian
SlovenščinaSlovenian
СрпскиSerbian
EestiEstonian
LatviešuLatvian
فارسیPersian
മലയാളംMalayalam
தமிழ்Tamil
اردوUrdu
Searching...
SoBrief
Python 3 Object-Oriented Programming

Python 3 Object-Oriented Programming

Python makes classes easy to write. Knowing when not to write one is the harder skill.
by Dusty Phillips 2010 431 pages
4.02
247 ratings
Listen
Immersive
V2.3
Amazon Kindle Audible
Try Full Access for 3 Days
Unlock listening & more!
Continue

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.

Analysis

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.

Analysis

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.

Analysis

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.

Analysis

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.

Analysis

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.

Analysis

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.

Analysis

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.

Analysis

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.

Analysis

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.

Analysis

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.

Summary in 30 Seconds
Create a class only when data and the behavior that uses it belong together; otherwise a function or built-in container is clearer. Keep public interfaces small and prefer composition to inheritance, with duck typing when behavior suffices. Raise specific exceptions and always release resources. Write tests first to shape the API, and treat coverage percentages skeptically. Match concurrency to the bottleneck: threads for waiting, processes for CPU work, and measure first.
Contains spoilers

Last updated:

Report Issue

Review Summary

4.02 out of 5
Average of 247 ratings from Goodreads and Amazon.

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.

Your rating:
4.44
94 ratings
Want to read the full book?

Glossary

Duck typing

Behavior-based compatibility

A 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 parts

A 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 behavior

A 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 requirements

A 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 access

A 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 cleanup

An 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 producer

An 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 routine

A 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 implementation

A 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 lock

A 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 memory

A 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.

About the Author

Dusty Phillips is an experienced open source programmer with over 15 years of Python programming expertise. He is known for his ability to simplify complex programming concepts, making them accessible to beginners and intermediate programmers. Phillips' writing style is praised for being engaging and practical, using real-world examples to illustrate abstract concepts. His work on Python 3 Object-oriented Programming demonstrates his deep understanding of both Python and object-oriented programming principles. Phillips is attentive to reader feedback, as evidenced by improvements made in the second edition of his book. His expertise extends beyond basic Python, covering advanced topics like concurrency and design patterns.

Download PDF

To save this Python 3 Object-Oriented Programming summary for later, download the free PDF. You can print it out, or read offline at your convenience.
Download PDF
File size: 0.35 MB     Pages: 17

Download EPUB

To read this Python 3 Object-Oriented Programming summary on your e-reader device or app, download the free EPUB. The .epub digital book format is ideal for reading ebooks on phones, tablets, and e-readers.
Download EPUB
File size: 1.41 MB     Pages: 21
Want to read the full book?
Follow
Listen
Home
Swipe
Library
Get App
Try Full Access for 3 Days
Listen, bookmark, and more
Compare Features Free Pro
📖 Read Summaries
Read unlimited summaries. Free users get 3 per month
🎧 Listen to Summaries
Listen to unlimited summaries in 40 languages
—
❤️ Unlimited Bookmarks
Free users are limited to 4
—
📜 Unlimited History
Free users are limited to 4
—
📥 Unlimited Downloads
Free users are limited to 1
—
Risk-Free Timeline
Today: Get Instant Access
Listen to full summaries of 26,000+ books. That's 12,000+ hours of audio!
Day 2: Trial Reminder
We'll send you a notification that your trial is ending soon.
Day 3: Your subscription begins
You'll be charged on Nov 24,
cancel anytime before.
Consume 2.8× More Books
2.8× more books Listening Reading
Our users love us
1M+ readers
Trustpilot Rating
TrustPilot
4.6 Excellent
This site is a total game-changer. I've been flying through book summaries like never before. Highly, highly recommend.
— Dave G
Worth my money and time, and really well made. I've never seen this quality of summaries on other websites. Very helpful!
— Em
Highly recommended!! Fantastic service. Perfect for those that want a little more than a teaser but not all the intricate details of a full audio book.
— Greg M
Save 62%
Yearly
$119.88 $44.99/year/yr
$3.75/mo
Monthly
$9.99/mo
Start a 3-Day Free Trial
3 days free, then $44.99/year. Cancel anytime.
Unlock a world of fiction & nonfiction books
26,000+ books for the price of 2 books
Read any book in 10 minutes
Discover new books like Tinder
Request any book if it's not summarized
Read more books than anyone you know
#1 app for book lovers
Lifelike & immersive summaries
30-day money-back guarantee
Download summaries in EPUBs or PDFs
Cancel anytime in a few clicks

Why one summary?

Scanner
Find a barcode to scan

⭐
⭐
⭐
We have a special gift for you
Open
38% off
DISCOUNT FOR YOU
⭐
⭐
⭐
$79.99
$49.99/year
Only $4.16 per month
Continue
2 taps to start, super easy to cancel
Settings
General
Widget
Loading...