Python Programming with Design Patterns, 1st edition

  • James W. Cooper

Your access includes:

  • Search, highlight, and take notes
  • Easily create flashcards
  • Use the app for access anywhere
  • 14-day refund guarantee

$10.99per month

4-month term, pay monthly or pay $43.96

Learn more, spend less

  • Special partners and offers

    Enjoy perks from special partners and offers for students

  • Find it fast

    Quickly navigate your eTextbook with search

  • Stay organized

    Access all your eTextbooks in one place

  • Easily continue access

    Keep learning with auto-renew


Improve Your Python Code with Modern Object-Oriented Design Patterns

To write clean, efficient, maintainable code, developers everywhere turn to design patterns. Now there's a Python-specific patterns guide that's friendly and practical enough for every Python developer, regardless of experience.

Best-selling patterns author James W. Cooper presents visual, example-driven explanations of 23 proven patterns for writing superior object-oriented code. Through clear and intuitive code samples, he introduces modern techniques for creating Python objects that interact effectively in powerful, flexible programs. Python newcomers--including those moving from other languages--will find a succinct introduction designed to get them up to speed fast.

Cooper's wide-ranging patterns coverage addresses abstract classes, multiple inheritance, GUI programming and widgets, graphical classes, drawing and plotting, math, databases, Python decorators, images, threads, iterators, creating executable code, and more. Throughout, his informal visual presentation makes patterns far easier to work with--so you can confidently build sophisticated programs that use Python's rich capabilities.

  • Review the essentials of Python objects and visual programming
  • Learn what design patterns are, and how they help you write better code
  • Use creational patterns to enhance flexibility and avoid unnecessary complexity
  • Apply structural patterns to ensure that program elements work together well in large programs
  • Optimize communication between objects with behavioral patterns

Published by Addison-Wesley Professional (December 17th 2021) - Copyright © 2022

ISBN-13: 9780137676767

Subject: Programming - Intermediate/Advanced

Category: Python

Table of contents

Preface     xxi


The tkinter Library     2

GitHub     2

Chapter 1  Introduction to Objects     5

The Class __init__ Method     6

Variables Inside a Class     6

Collections of Classes     7

Inheritance     8

Derived Classes Created with Revised Methods     8

Multiple Inheritance     8

Drawing a Rectangle and a Square     10

Visibility of Variables     12

    Properties     13

    Local Variables     13

Types in Python     13

Summary     14

Programs on GitHub     15

Chapter 2  Visual Programming in Python     17

Importing Fewer Names     19

Creating an Object-Oriented Version     19

Using Message Boxes     21

Using File Dialogs     22

Understanding Options for the Pack Layout Manager     23

Using the ttk Libraries     24

Responding to User Input     25

    Adding Two Numbers     26

    Catching the Error     26

Applying Colors in tkinter     27

Creating Radio Buttons     27

    Using a Class-Level Variable     30

Communicating Between Classes     30

Using the Grid Layout     30

Creating Checkbuttons     32

    Disabling Check Boxes     32

Adding Menus to Windows     35

Using the LabelFrame     39

Moving On     40

Examples on GitHub     40

Chapter 3  Visual Programming of Tables of Data     41

Creating a Listbox     42

    Displaying the State Data     44

Using a Combobox     46

The Treeview Widget     47

    Inserting Tree Nodes     50

Moving On     51

Example Code on GitHub     51

Chapter 4  What Are Design Patterns?     53

Defining Design Patterns     54

The Learning Process     55

Notes on Object-Oriented Approaches     56

Python Design Patterns     57

References     57


Chapter 5  The Factory Pattern     61

How a Factory Works     61

Sample Code     62

The Two Subclasses     62

Building the Simple Factory     63

    Using the Factory     63

    A Simple GUI     64

Factory Patterns in Math Computation     65

Programs on GitHub     65

Thought Questions     66

Chapter 6  The Factory Method Pattern     67

The Swimmer Class     68

The Event Classes     69

Straight Seeding     70

    Circle Seeding     71

Our Seeding Program     72

Other Factories     74

When to Use a Factory Method     74

Programs on GitHub     74

Chapter 7  The Abstract Factory Pattern     75

A GardenMaker Factory     75

How the User Interface Works     77

Consequences of the Abstract Factory Pattern     77

Thought Questions     78

Code on GitHub     78

Chapter 8  The Singleton Pattern     79

Throwing the Exception     80

Creating an Instance of the Class     80

Static Classes As Singleton Patterns     81

Finding the Singletons in a Large Program     81

Other Consequences of the Singleton Pattern     82

Sample Code on GitHub     82

Chapter 9  The Builder Pattern     83

An Investment Tracker     84

Calling the Builders     86

    The List Box Builder     87

    The Checkbox Builder     88

Displaying the Selected Securities     89

Consequences of the Builder Pattern     89

Thought Questions     89

Sample Code on GitHub     89

Chapter 10  The Prototype Pattern     91

Cloning in Python     91

Using the Prototype     92

Consequences of the Prototype Pattern     94

Sample Code on GitHub     94

Chapter 11  Summary of Creational Patterns     95


Chapter 12  The Adapter Pattern     99

Moving Data Between Lists     99

Making an Adapter     101

    The Class Adapter     103

    Two-Way Adapters     103

    Pluggable Adapters     103

Programs on GitHub     103

Chapter 13  The Bridge Pattern     105

Creating the User Interface     107

Extending the Bridge     108

Consequences of the Bridge Pattern     109

Programs on GitHub     110

Chapter 14  The Composite Pattern     111

An Implementation of a Composite     112

Salary Computation     112

The Employee Classes     112

The Boss Class     113

Building the Employee Tree     114

Printing the Employee Tree     114

Creating a Treeview of the Composite     116

Using Doubly Linked Lists     117

Consequences of the Composite Pattern     118

A Simple Composite     119

Other Implementation Issues     119

    Dealing with Recursive Calls     119

    Ordering Components     120

    Caching Results     120

Programs on GitHub     120

Chapter 15  The Decorator Pattern     121

Decorating a Button     121

Using a Decorator     122

Using Nonvisual Decorators     123

    Decorated Code     124

The dataclass Decorator     125

Using dataclass with Default Values     126

Decorators, Adapters, and Composites     126

Consequences of the Decorator Pattern     126

Programs on GitHub     127

Chapter 16  The Facade Pattern     129

Building the Façade Classes     131

Creating Databases and Tables     135

Using the SQLite Version     136

Consequences of the Façade     137

Programs on GitHub     137

Notes on MySQL     137

Using SQLite     138

References     138

Chapter 17  The Flyweight Pattern     139

What Are Flyweights?     139

Example Code     140

Selecting a Folder     142

Copy-on-Write Objects     143

Program on GitHub     143

Chapter 18  The Proxy Pattern     145

Using the Pillow Image Library     145

Displaying an Image Using PIL     146

Using Threads to Handle Image Loading     146

Logging from Threads     149

Copy-on-Write     149

Comparing Related Patterns     149

Programs on GitHub     150

Chapter 19  Summary of Structural Patterns     151


Chapter 20  Chain of Responsibility Pattern     155

When to Use the Chain     156

Sample Code     156

The Listboxes     159

Programming a Help System     160

Receiving the Help Command     161

The First Case     162

A Chain or a Tree?     163

Kinds of Requests     164

Consequences of the Chain of Responsibility     164

Programs on GitHub     165

Chapter 21  The Command Pattern     167

When to Use the Command Pattern     167

Command Objects     168

A Keyboard Example     168

Calling the Command Objects     170

Building Command Objects     171

The Command Pattern     172

Consequences of the Command Pattern     172

Providing the Undo Function     172

    Creating the Red and Blue Buttons     175

    Undoing the Lines     175

Summary     176

References     176

Programs on GitHub     176

Chapter 22  The Interpreter Pattern     177

When to Use an Interpreter     177

Where the Pattern Can Be Helpful     177

A Simple Report Example     178

Interpreting the Language     179

How Parsing Works     180

    Sorting Using attrgetter()     181

    The Print Verb     182

The Console Interface     182

The User Interface     183

Consequences of the Interpreter Pattern     184

Programs on GitHub     185

Chapter 23  The Iterator Pattern     187

Why We Use Iterators     187

Iterators in Python     187

A Fibonacci Iterator     188

    Getting the Iterator     189

Filtered Iterators     189

The Iterator Generator     191

A Fibonacci Iterator     191

Generators in Classes     192

Consequences of the Iterator Pattern     192

Programs on GitHub     193

Chapter 24  The Mediator Pattern     195

An Example System     195

Interactions Between Controls     197

Sample Code     198

Mediators and Command Objects     199

Consequences of the Mediator Pattern     200

Single Interface Mediators     200

Programs on GitHub     201

Chapter 25  The Memento Pattern     203

When to Use a Memento     203

Sample Code     204

Consequences of the Memento Pattern     209

Programs on GitHub     209

Chapter 26  The Observer Pattern     211

Example Program for Watching Colors Change     212

The Message to the Media     215

Consequences of the Observer Pattern     215

Programs on GitHub     215

Chapter 27  The State Pattern     217

Sample Code     217

Switching Between States     221

How the Mediator Interacts with the State

State Transitions     224

Programs on GitHub     224

Chapter 28  The Strategy Pattern     225

Why We Use the Strategy Pattern     225

Sample Code     226

The Context     227

The Program Commands     227

The Line and Bar Graph Strategies     228

Consequences of the Strategy Pattern     230

Programs on GitHub     231

Chapter 29  The Template Pattern     233

Why We Use Template Patterns     233

Kinds of Methods in a Template Class     234

Sample Code     234

    Drawing a Standard Triangle     235

    Drawing an Isosceles Triangle     236

The Triangle Drawing Program     237

Templates and Callbacks     238

Summary and Consequences     238

Example Code on GitHub     238

Chapter 30  The Visitor Pattern     239

When to Use the Visitor Pattern     239

Working with the Visitor Pattern     241

Sample Code     241

Visiting Each Class     242

Visiting Several Classes     242

Bosses Are Employees, Too     243

Double Dispatching     245

Traversing a Series of Classes     245

Consequences of the Visitor Pattern     245

Example Code on GitHub     245


Chapter 31  Variables and Syntax in Python     249

Data Types     250

Numeric Constants     250

Strings     250

Character Constants     251

Variables     252

Complex Numbers     253

Integer Division     253

Multiple Equal Signs for Initialization     254

A Simple Python Program     254

Compiling and Running This Program     255

Arithmetic Operators     255

    Bitwise Operators     255

Combined Arithmetic and Assignment Statements     256

Comparison Operators     256

The input Statement     257

PEP 8 Standards     258

    Variable and Function Names     258

    Constants     258

    Class Names     258

    Indentation and Spacing     259

    Comments     259

    Docstrings     259

String Methods     260

Examples on GitHub     261

Chapter 32  Making Decisions in Python     263

elif is “else if”     263

Combining Conditions     264

The Most Common Mistake     264

Looping Statements in Python     265

    The for Loop and Lists     265

    Using range in if Statements     266

Using break and continue     266

    The continue Statement     267

Python Line Length     267

The print Function     267

Formatting Numbers     268

    C and Java Style Formatting     269

    The format string Function     269

    f-string Formatting     269

    Comma-Separated Numbers     270

    Strings     270

Formatting Dates     271

Using the Python match Function     271

    Pattern Matching     272

Reference     273

Moving On     273

Sample Code on GitHub     273

Chapter 33  Development Environments     275

IDLE     275

Thonny     275

PyCharm     276

Visual Studio     276

Other Development Environments     276

    LiClipse     276

    Jupyter Notebook     277

    Google Colaboratory     277

    Anaconda     277

    Wing     278

Command-Line Execution     278

CPython, IPython, and Jython     278

Chapter 34  Python Collections and Files     279

Slicing     279

Slicing Strings     280

    Negative Indexes     281

    String Prefix and Suffix Removal     281

Changing List Contents     281

Copying a List     282

Reading Files     282

    Using the with Loop     283

Handling Exceptions     284

Using Dictionaries     284

    Combining Dictionaries     286

Using Tuples     286

Using Sets     287

Using the map Function     287

Writing a Complete Program     288

    Impenetrable Coding     288

Using List Comprehension     289

Sample Programs on GitHub     290

Chapter 35  Functions     291

Returning a Tuple     292

Where Does the Program Start?     292

Summary     293

Programs on GitHub     293

Appendix A  Running Python Programs     295

If You Have Python Installed     295

    Shortcuts     295

Creating an Executable Python Program     296

Command-Line Arguments     297

Index     299

Your questions answered

Pearson+ is your one-stop shop, with eTextbooks and study videos designed to help students get better grades in college.

A Pearson eTextbook is an easy‑to‑use digital version of the book. You'll get upgraded study tools, including enhanced search, highlights and notes, flashcards and audio. Plus learn on the go with the Pearson+ app.

Your eTextbook subscription gives you access for 4 months. You can make a one‑time payment for the initial 4‑month term or pay monthly. If you opt for monthly payments, we will charge your payment method each month until your 4‑month term ends. You can turn on auto‑renew in My account at any time to continue your subscription before your 4‑month term ends.

When you purchase an eTextbook subscription, it will last 4 months. You can renew your subscription by selecting Extend subscription on the Manage subscription page in My account before your initial term ends.

If you extend your subscription, we'll automatically charge you every month. If you made a one‑time payment for your initial 4‑month term, you'll now pay monthly. To make sure your learning is uninterrupted, please check your card details.

To avoid the next payment charge, select Cancel subscription on the Manage subscription page in My account before the renewal date. You can subscribe again in the future by purchasing another eTextbook subscription.

Channels is a video platform with thousands of explanations, solutions and practice problems to help you do homework and prep for exams. Videos are personalized to your course, and tutors walk you through solutions. Plus, interactive AI‑powered summaries and a social community help you better understand lessons from class.

Channels is an additional tool to help you with your studies. This means you can use Channels even if your course uses a non‑Pearson textbook.

When you choose a Channels subscription, you're signing up for a 1‑month, 3‑month or 12‑month term and you make an upfront payment for your subscription. By default, these subscriptions auto‑renew at the frequency you select during checkout.

When you purchase a Channels subscription it will last 1 month, 3 months or 12 months, depending on the plan you chose. Your subscription will automatically renew at the end of your term unless you cancel it.

We use your credit card to renew your subscription automatically. To make sure your learning is uninterrupted, please check your card details.