Sie sind auf Seite 1von 21

Python: Master the Art of

Design Patterns

(QVXUH\RXUFRGHLVVOHHN
HIILFLHQWDQGHOHJDQWE\PDVWHULQJ
SRZHUIXO3\WKRQGHVLJQSDWWHUQV

A course in three modules

BIRMINGHAM - MUMBAI
Python: Master the Art of Design Patterns
Copyright 2016 Packt Publishing

All rights reserved. No part of this course may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.

Every effort has been made in the preparation of this course to ensure the accuracy
of the information presented. However, the information contained in this course
is sold without warranty, either express or implied. Neither the authors, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this course.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this course by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

Published on: 6HSWHPEHU

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.

ISBN 
www.packtpub.com
Credits

Authors Content Development Editor


Dusty Phillips Trusha Shriyan
Chetan Giridhar
Sakis Kasampalis Graphics
Kirk DPhena

Reviewers
AMahdy AbdElAziz Production Coordinator
Shantanu N. Zagade
Grigoriy Beziuk
Krishna Bharadwaj
Justin Cano
Anthony Petitbois
Claudio Rodriguez
Maurice HT Ling
Evan Dempsey
Amitabh Sharma
Yogendra Sharma
3DWU\FMD6]DERZVND
Preface
Python is an object-oriented, scripting language that is used in wide range of
categories. In software engineering, a design pattern is a recommended solution
to a software design problem. Although not new, design patterns remain one of
the hottest topics in software engineering. Python 3 is more versatile and easier to
use than ever. It runs on all major platforms in a huge array of use cases. Coding
in Python minimizes development time and increases productivity in comparison
to other languages. Clean, maintainable code is easy to both read and write using
Pythons clear, concise syntax.

If you love designing and want to learn everything about it but have no idea where
to begin, then this course is built just for you. This learning path is divided into three
modules which will take you in this incredible journey of design patterns.

What this learning path covers


Module 1, Python 3 Object-oriented Programming - Second Edition, This module is
ORRVHO\GLYLGHGLQWRIRXUPDMRUSDUWV,QWKHUVWIRXUFKDSWHUVZHZLOOGLYHLQWRWKH
formal principles of object-oriented programming and how Python leverages them.
In chapters 5 through 8, we will cover some of Pythons idiosyncratic applications
of these principles by learning how they are applied to a variety of Pythons built-in
IXQFWLRQV&KDSWHUVWKURXJKFRYHUGHVLJQSDWWHUQVDQGWKHQDOWZRFKDSWHUV
discuss two bonus topics related to Python programming that may be of interest.

[i]
Preface

Module 2, Learning Python Design Patterns - Second Edition, Building on the success of the
previous edition, Learning Python Design Patterns, Second Edition will help you implement
real-world scenarios with Pythons latest release, Python v3.5. We start by introducing design
patterns from the Python perspective. As you progress through the module, you will learn
about Singleton patterns, Factory patterns, and Faade patterns in detail. After this, well look
at how to control object access with proxy patterns. It also covers observer patterns, command
patterns, and compound patterns. By the end of the module, you will have enhanced your
professional abilities in software architecture, design, and development.

Module 3, DWW, This module focuses on design patterns


in Python. Python is different than most common programming languages used
in popular design patterns books (usually Java [FFBS04] or C++ [GOF95]). It
VXSSRUWVGXFNW\SLQJIXQFWLRQVDUHUVWFODVVFLWL]HQVDQGVRPHSDWWHUQV IRU
instance, iterator and decorator) are built-in features. The intent of this module is to
demonstrate the most fundamental design patterns, not all patterns that have been
documented so far [j.mp/wikidpc]. The code examples focus on using idiomatic
Python when applicable [j.mp/idiompyt]. If you are not familiar with the Zen of
Python, it is a good idea to open the Python REPL right now and execute import
this. The Zen of Python is both amusing and meaningful.

What you need for this learning path


All the examples in this course rely on the Python 3 interpreter. Make sure you are
not using Python 2.7 or earlier. At the time of writing, Python 3.4 was the latest
release of Python. Most examples will work on earlier revisions of Python 3, but you
are encouraged to use the latest version to minimize frustration.

All of the examples should run on any operating system supported by Python. If this
is not the case, please report it as a bug.

Some of the examples need a working Internet connection. Youll probably want to
have one of these for extracurricular research and debugging anyway!

In addition, some of the examples in this course rely on third-party libraries that do
not ship with Python. These are introduced within the course at the time they are
used, so you do not need to install them in advance. However, for completeness,
here is a list:

x pip
x requests
x pillow
x bitarray

[ ii ]
Preface

Who this learning path is for


Python developers and software architects who care about software design
principles and details of application development aspects in Python. Programmers of
RWKHUODQJXDJHVZKRDUHLQWHUHVWHGLQ3\WKRQFDQDOVREHQHWIURPWKLVFRXUVH

Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this coursewhat you liked or disliked. Reader feedback is important for us as it
helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail feedback@packtpub.com, and mention


the courses title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support
Now that you are the proud owner of a Packt course, we have a number of things to
help you to get the most from your purchase.

Downloading the example code


<RXFDQGRZQORDGWKHH[DPSOHFRGHOHVIRUWKLVFRXUVHIURP\RXUDFFRXQWDW
http://www.packtpub.com. If you purchased this course elsewhere, you can visit
http://www.packtpub.com/supportDQGUHJLVWHUWRKDYHWKHOHVHPDLOHGGLUHFWO\
to you.

<RXFDQGRZQORDGWKHFRGHOHVE\IROORZLQJWKHVHVWHSV

1. Log in or register to our website using your e-mail address and password.
2. Hover the mouse pointer on the SUPPORT tab at the top.
3. Click on Code Downloads & Errata.
4. Enter the name of the course in the Search box.
5. 6HOHFWWKHFRXUVHIRUZKLFK\RXUHORRNLQJWRGRZQORDGWKHFRGHOHV
6. Choose from the drop-down menu where you purchased this course from.
7. Click on Code Download.

[ iii ]
Preface

<RXFDQDOVRGRZQORDGWKHFRGHOHVE\FOLFNLQJRQWKHCode Files button on the


courses webpage at the Packt Publishing website. This page can be accessed by
entering the courses name in the Search box. Please note that you need to be logged
in to your Packt account.

2QFHWKHOHLVGRZQORDGHGSOHDVHPDNHVXUHWKDW\RXXQ]LSRUH[WUDFWWKHIROGHU
using the latest version of:

 WinRAR / 7-Zip for Windows


 Zipeg / iZip / UnRarX for Mac
 7-Zip / PeaZip for Linux

The code bundle for the course is also hosted on GitHub at https://github.com/
PacktPublishing/Python_Master-the-Art-of-Design-Patterns. We also have
other code bundles from our rich catalog of books, videos, and courses available at
https://github.com/PacktPublishing/. Check them out!

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
GRKDSSHQ,I\RXQGDPLVWDNHLQRQHRIRXUFRXUVHVPD\EHDPLVWDNHLQWKHWH[W
or the codewe would be grateful if you could report this to us. By doing so, you
can save other readers from frustration and help us improve subsequent versions
RIWKLVFRXUVH,I\RXQGDQ\HUUDWDSOHDVHUHSRUWWKHPE\YLVLWLQJhttp://www.
packtpub.com/submit-errata, selecting your course, clicking on the Errata
Submission Form link, and entering the details of your errata. Once your errata are
YHULHG\RXUVXEPLVVLRQZLOOEHDFFHSWHGDQGWKHHUUDWDZLOOEHXSORDGHGWRRXU
website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/


content/supportDQGHQWHUWKHQDPHRIWKHFRXUVHLQWKHVHDUFKHOG7KHUHTXLUHG
information will appear under the Errata section.

[ iv ]
Preface

Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all
media. At Packt, we take the protection of our copyright and licenses very seriously.
If you come across any illegal copies of our works in any form on the Internet, please
provide us with the location address or website name immediately so that we can
pursue a remedy.

Please contact us at copyright@packtpub.com with a link to the suspected pirated


material.

We appreciate your help in protecting our authors and our ability to bring you
valuable content.

Questions
If you have a problem with any aspect of this course, you can contact us at
questions@packtpub.com, and we will do our best to address the problem.

[v]
Module 1: Python 3 Object-Oriented Programming - Second
Edition

Chapter 1: Object-oriented Design 3


Introducing object-oriented 3
Objects and classes 5
Specifying attributes and behaviors 7
Hiding details and creating the
public interface 11
Composition 13
Inheritance 16
Case study 20
Exercises 27
Summary 28
Chapter 2: Objects in Python 29
Creating Python classes 29
Modules and packages 39
Organizing module contents 45
Who can access my data? 48
Third-party libraries 50
Case study 51
Exercises 60
Summary 60

[i]
Table of Contents

Chapter 3: When Objects Are Alike 61


Basic inheritance 61
Multiple inheritance 67
Polymorphism 77
Abstract base classes 80
Case study 84
Exercises 97
Summary 98
Chapter 4: Expecting the Unexpected 99
Raising exceptions 100
Case study 116
Exercises 125
Summary 126
Chapter 5: When to Use Object-oriented Programming 127
Treat objects as objects 127
Adding behavior to class data with properties 131
Manager objects 140
Case study 147
Exercises 155
Summary 156
Chapter 6: Python Data Structures 157
Empty objects 157
Tuples and named tuples 159
Dictionaries 162
Lists 169
Sets 175
Extending built-ins 179
Queues 184
Case study 190
Exercises 196
Summary 197
Chapter 7: Python Object-oriented Shortcuts 199
Python built-in functions 199
An alternative to method overloading 207
Functions are objects too 215
Case study 221
Exercises 228
Summary 229

[ ii ]
Table of Contents

Chapter 8: Strings and Serialization 231


Strings 231
Regular expressions 246
Serializing objects 254
Case study 262
Exercises 267
Summary 269
Chapter 9: The Iterator Pattern 271
Design patterns in brief 271
Iterators 272
Comprehensions 275
Generators 281
Coroutines 286
Case study 293
Exercises 300
Summary 301
Chapter 10: Python Design Patterns I 303
The decorator pattern 303
The observer pattern 309
The strategy pattern 312
The state pattern 315
The singleton pattern 322
The template pattern 327
Exercises 331
Summary 331
Chapter 11: Python Design Patterns II 333
The adapter pattern 333
The facade pattern 337
7KH\ZHLJKWSDWWHUQ 
The command pattern 343
The abstract factory pattern 348
The composite pattern 353
Exercises 357
Summary 358
Chapter 12: Testing Object-oriented Programs 359
Why test? 359
Unit testing 362
Testing with py.test 370
Imitating expensive objects 380

[ iii ]
Table of Contents

How much testing is enough? 384


Case study 387
Exercises 393
Summary 394
Chapter 13: Concurrency 395
Threads 396
Multiprocessing 401
Futures 408
AsyncIO 411
Case study 420
Exercises 427
Summary 428

Module 2: Learning Python Design Patterns - Second


Edition

Chapter 1: Introduction to Design Patterns 431


Understanding object-oriented programming 432
Major aspects of object-oriented programming 433
Object-oriented design principles 436
The concept of design patterns 438
Patterns for dynamic languages 441
Classifying patterns 441
Summary 442
Chapter 2: The Singleton Design Pattern 443
Understanding the Singleton design pattern 444
Lazy instantiation in the Singleton pattern 445
Module-level Singletons 446
The Monostate Singleton pattern 446
Singletons and metaclasses 448
A real-world scenario the Singleton pattern, part 1 449
A real-world scenario the Singleton pattern, part 2 451
Drawbacks of the Singleton pattern 453
Summary 454
Chapter 3: The Factory Pattern Building Factories
to Create Objects 455
Understanding the Factory pattern 455
The Simple Factory pattern 456

[ iv ]
Table of Contents

The Factory Method pattern 458


The Abstract Factory pattern 462
The Factory method versus Abstract Factory method 466
Summary 467
Chapter 4: The Faade Pattern Being Adaptive with Faade 469
Understanding Structural design patterns 470
Understanding the Faade design pattern 470
A UML class diagram 471
Implementing the Faade pattern in the real world 473
The principle of least knowledge 477
Frequently asked questions 477
Summary 478
Chapter 5: The Proxy Pattern Controlling Object Access 479
Understanding the Proxy design pattern 480
A UML class diagram for the Proxy pattern 482
Understanding different types of Proxies 483
The Proxy pattern in the real world 484
Advantages of the Proxy pattern 488
Comparing the Faade and Proxy patterns 488
Frequently asked questions 488
Summary 489
Chapter 6: The Observer Pattern Keeping Objects in the Know 491
Introducing Behavioral patterns 492
Understanding the Observer design pattern 492
The Observer pattern in the real world 495
The Observer pattern methods 499
Loose coupling and the Observer pattern 500
The Observer pattern advantages and disadvantages 501
Frequently asked questions 501
Summary 502
Chapter 7: The Command Pattern Encapsulating Invocation 503
Introducing the Command pattern 504
Understanding the Command design pattern 504
Implementing the Command pattern in the real world 509
Advantages and disadvantages of Command patterns 513
Frequently asked questions 513
Summary 514

[v]
Table of Contents

Chapter 8: The Template Method Pattern Encapsulating


Algorithm 515
'HQLQJWKH7HPSODWH0HWKRGSDWWHUQ 
The Template Method pattern in the real world 522
The Template Method pattern hooks 526
The Hollywood principle and the Template Method 527
The advantages and disadvantages of the Template Method pattern 527
Frequently asked questions 528
Summary 528
Chapter 9: Model-View-Controller Compound Patterns 529
An introduction to Compound patterns 530
The Model-View-Controller pattern 530
A UML class diagram for the MVC design pattern 535
The MVC pattern in the real world 537
%HQHWVRIWKH09&SDWWHUQ 
Frequently asked questions 545
Summary 545
Chapter 10: The State Design Pattern 547
'HQLQJWKH6WDWHGHVLJQSDWWHUQ 
A simple example of the State design pattern 550
Advantages/disadvantages of the State pattern 555
Summary 556
Chapter 11: AntiPatterns 557
An introduction to AntiPatterns 558
Software development AntiPatterns 559
Software architecture AntiPatterns 562
Summary 564

Module 3: Mastering Python Design Patterns

Chapter 1: The Factory Pattern 567


Factory Method 567
Abstract Factory 578
Summary 585
Chapter 2: The Builder Pattern 587
A real-life example 588
A software example 588
Use cases 589

[ vi ]
Table of Contents

Implementation 592
Summary 601
Chapter 3: The Prototype Pattern 603
A real-life example 605
A software example 606
Use cases 606
Implementation 607
Summary 612
Chapter 4: The Adapter Pattern 615
A real-life example 616
A software example 616
Use cases 617
Implementation 617
Summary 621
Chapter 5: The Decorator Pattern 623
A real-life example 624
A software example 625
Use cases 625
Implementation 626
Summary 631
Chapter 6: The Facade Pattern 633
A real-life example 634
A software example 634
Use cases 635
Implementation 635
Summary 641
Chapter 7: The Flyweight Pattern 643
A real-life example 644
A software example 644
Use cases 644
Implementation 645
Summary 650
Chapter 8: The Model-View-Controller Pattern 651
A real-life example 652
A software example 652
Use cases 653
Implementation 654
Summary 658

[ vii ]
Table of Contents

Chapter 9: The Proxy Pattern 661


A real-life example 664
A software example 665
Use cases 665
Implementation 666
Summary 670
Chapter 10: The Chain of Responsibility Pattern 671
A real-life example 673
A software example 673
Use cases 674
Implementation 675
Summary 680
Chapter 11: The Command Pattern 683
A real-life example 684
A software example 684
Use cases 685
Implementation 685
Summary 693
Chapter 12: The Interpreter Pattern 695
A real-life example 696
A software example 696
Use cases 697
Implementation 698
Summary 705
Chapter 13: The Observer Pattern 707
A real-life example 707
A software example 708
Use cases 709
Implementation 709
Summary 716
Chapter 14: The State Pattern 717
A real-life example 719
A software example 720
Use cases 720
Implementation 720
Summary 727

[ viii ]
Table of Contents

Chapter 15: The Strategy Pattern 729


A real-life example 730
A software example 731
Use cases 732
Implementation 733
Summary 738
Chapter 16: The Template Pattern 739
A real-life example 745
A software example 746
Use cases 746
Implementation 747
Summary 750
Appendix: Bibliography 751

[ ix ]

Das könnte Ihnen auch gefallen