Home > Store

Python Programming with Design Patterns

Register your product to gain access to bonus material or receive a coupon.

Python Programming with Design Patterns

Best Value Purchase

Book + eBook Bundle

  • Your Price: $51.89
  • List Price: $83.98
  • Includes EPUB and PDF
  • About eBook Formats
  • This eBook includes the following formats, accessible from your Account page after purchase:

    ePub EPUB The open industry format known for its reflowable content and usability on supported mobile devices.

    Adobe Reader PDF The popular standard, used most often with the free Acrobat® Reader® software.

    This eBook requires no passwords or activation to read. We customize your eBook by discreetly watermarking it with your name, making it uniquely yours.

More Purchase Options

Book

  • Your Price: $39.99
  • List Price: $49.99
  • Usually ships in 24 hours.

eBook (Watermarked)

  • Your Price: $27.19
  • List Price: $33.99
  • Includes EPUB and PDF
  • About eBook Formats
  • This eBook includes the following formats, accessible from your Account page after purchase:

    ePub EPUB The open industry format known for its reflowable content and usability on supported mobile devices.

    Adobe Reader PDF The popular standard, used most often with the free Acrobat® Reader® software.

    This eBook requires no passwords or activation to read. We customize your eBook by discreetly watermarking it with your name, making it uniquely yours.

About

Features

  • Covers all of Python's principal features with working examples.
  • Covers all 23 Design Patterns with visual GUI examples to make the algorithms clearer.
  • Written in an accessible style.
  • Covers use of six different development environments with recommendations.
  • Complete downloadable code for all examples provided on GitHub.

Description

  • Copyright 2022
  • Dimensions: 7" x 9-1/8"
  • Pages: 352
  • Edition: 1st
  • Book
  • ISBN-10: 0-13-757993-4
  • ISBN-13: 978-0-13-757993-8

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

Sample Content

Online Sample Chapter

What Are Design Patterns?

Sample Pages

Download the sample pages (includes Chapter 4)

Table of Contents

Preface xxi

PART I: INTRODUCTION 1

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

PART II: CREATIONAL PATTERNS 59

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

PART III: STRUCTURAL PATTERNS 97

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

PART IV: BEHAVIORAL PATTERNS 153

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

PART V: A BRIEF INTRODUCTION TO PYTHON 247

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

Updates

Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020