Python 3 object oriented programming 3rd edition dusty phillips dusty phillips

Page 1

Python 3 Object Oriented Programming

3rd Edition Dusty Phillips [Dusty Phillips]

Visit to download the full and correct content document: https://textbookfull.com/product/python-3-object-oriented-programming-3rd-edition-du sty-phillips-dusty-phillips/

More products digital (pdf, epub, mobi) instant download maybe you interests ...

Swift

3 Object Oriented Programming Gaston C. Hillar

https://textbookfull.com/product/swift-3-object-orientedprogramming-gaston-c-hillar/

Deep Learning in Python An Object Oriented Programming 1st Edition Hong M. Lei [Lei

https://textbookfull.com/product/deep-learning-in-python-anobject-oriented-programming-1st-edition-hong-m-lei-lei/

Android Programming The Big Nerd Ranch Guide 2nd Edition Bill Phillips

https://textbookfull.com/product/android-programming-the-bignerd-ranch-guide-2nd-edition-bill-phillips/

Programming In C Object Oriented Features 1st Edition Laxmisha Rai

https://textbookfull.com/product/programming-in-c-objectoriented-features-1st-edition-laxmisha-rai/

Surgical Instrumentation Nancymarie Phillips

https://textbookfull.com/product/surgical-instrumentationnancymarie-phillips/

Astrophysics For Dummies Cynthia

Phillips

https://textbookfull.com/product/astrophysics-for-dummiescynthia-phillips/

C++ Programming: An Object-Oriented Approach, 1e ISE Behrouz A. Forouzan

https://textbookfull.com/product/c-programming-an-objectoriented-approach-1e-ise-behrouz-a-forouzan/

The American Challenge Reader Michael Phillips

https://textbookfull.com/product/the-american-challenge-readermichael-phillips/

Object Oriented Programming with SIMOTION Fundamentals Program Examples and Software Concepts According to IEC 61131 3 1st Edition Michael Braun

https://textbookfull.com/product/object-oriented-programmingwith-simotion-fundamentals-program-examples-and-softwareconcepts-according-to-iec-61131-3-1st-edition-michael-braun/

Python 3 Object-Oriented Programming

ThirdEdition

Build robust and maintainable software with object-oriented design patterns in Python 3.8

Dusty Phillips

BIRMINGHAM

- MUMBAI

Python 3 Object-Oriented Programming Third Edition

Copyright © 2018 Packt Publishing

All rights reserved. No part of this book 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 book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

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

Commissioning Editor: Richa Tripathi

Acquisition Editor: Chaitanya Nair

Content Development Editor: Rohit Kumar Singh

Technical Editor: Ketan Kamble

Copy Editor: Safis Editing

Project Coordinator: Vaidehi Sawant

Proofreader: Safis Editing

Indexer: Mariammal Chettiyar

Graphics: Alishon Mendonsa

Production Coordinator: Aparna Bhagat

First published: July 2010

Second edition: August 2015

Third edition: October 2018

Production reference: 2051118

Published by Packt Publishing Ltd.

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

ISBN 978-1-78961-585-2

www.packt.com

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

mapt.io

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

Packt.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at customercare@packtpub.com for more details.

At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

Contributors

About the author

Dusty Phillips is a Canadian software developer and author currently living in New Brunswick. He has been active in the open source community for two decades and has been programming in Python for nearly as long. He holds a master's degree in computer science and has worked for Facebook, the United Nations, and several start-ups. He's currently researching privacy-preserving technology at beanstalk.network.

Python3Object-OrientedProgrammingwas his first book. He has also written CreatingAppsinKivy, and self-published Hacking Happy, a journey to mental wellness for the technically inclined. A work of fiction is coming as well, so stay tuned!

About the reviewers

Yogendra Sharma is a developer with experience of the architecture, design, and development of scalable and distributed applications. He was awarded a bachelor's degree from Rajasthan Technical University in computer science. With a core interest in microservices and Spring, he also has hands-on experience technologies such as AWS Cloud, Python, J2EE, Node.js, JavaScript, Angular, MongoDB, and Docker. Currently, he works as an IoT and cloud architect at Intelizign Engineering Services, Pune.

Josh Smith has been coding professionally in Python, JavaScript, and C# for over 5 years, but has loved programming since learning Pascal over 20 years ago. Python is his default language for personal and professional projects. He believes code should be simple, goaloriented, and maintainable. Josh works in data automation and lives in St. Louis, Missouri, with his wife and two children.

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit autho rs.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

Python 3 Object-Oriented Programming Third Edition

Packt Upsell

Why subscribe?

Packt.com

Contributors

About the author

About the reviewers

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Conventions used

Get in touch

Reviews

1. Object-Oriented Design

Introducing object-oriented

Objects and classes

Specifying attributes and behaviors

Data describes objects

Behaviors are actions

Hiding details and creating the public interface

Composition

Inheritance

Inheritance provides abstraction

Multiple inheritance

Case study

Exercises

Summary

2. Objects in Python

Creating Python classes

Adding attributes

Making it do something

Talking to yourself

More arguments

Initializing the object

Explaining yourself

Modules and packages

Organizing modules

Absolute imports

Relative imports

Organizing module content

Who can access my data?

Third-party libraries

Case study

Exercises

Summary

3. When Objects Are Alike

Basic inheritance

Extending built-ins

Overriding and super

Multiple inheritance

The diamond problem

Different sets of arguments

Polymorphism

Abstract base classes

Using an abstract base class

Creating an abstract base class

Demystifying the magic

Case study

Exercises

Summary

4. Expecting the Unexpected

Raising exceptions

Raising an exception

The effects of an exception

Handling exceptions

The exception hierarchy

Defining our own exceptions

Case study

Exercises

Summary

5. When to Use Object-Oriented Programming

Treat objects as objects

Adding behaviors to class data with properties

Properties in detail

Decorators – another way to create properties

Deciding when to use properties

Manager objects

Removing duplicate code

In practice

Case study

Exercises

Summary

6. Python Data Structures

Empty objects

Tuples and named tuples

Named tuples

Dataclasses

Dictionaries

Dictionary use cases

Using defaultdict

Counter

Lists

Sorting lists

Sets

Extending built-in functions

Case study

Exercises

Summary

7. Python Object-Oriented Shortcuts

Python built-in functions

The len() function

Reversed

Enumerate

File I/O

Placing it in context

An alternative to method overloading

Default arguments

Variable argument lists

Unpacking arguments

Functions are objects too

Using functions as attributes

Callable objects

Case study

Exercises

Summary

8. Strings and Serialization

Strings

String manipulation

String formatting

Escaping braces

f-strings can contain Python code

Making it look right

Custom formatters

The format method

Strings are Unicode

Converting bytes to text

Converting text to bytes

Mutable byte strings

Regular expressions

Matching patterns

Matching a selection of characters

Escaping characters

Matching multiple characters

Grouping patterns together

Getting information from regular expressions

Making repeated regular expressions efficient

Filesystem paths

Serializing objects

Customizing pickles

Serializing web objects

Case study

Exercises

Summary

9. The Iterator Pattern

Design patterns in brief

Iterators

The iterator protocol

Comprehensions

List comprehensions

Set and dictionary comprehensions

Generator expressions

Generators

Yield items from another iterable

Coroutines

Back to log parsing

Closing coroutines and throwing exceptions

The relationship between coroutines, generators, and functions

Case study

Exercises

Summary

10. Python Design Patterns I

The decorator pattern

A decorator example

Decorators in Python

The observer pattern

An observer example

The strategy pattern

A strategy example

Strategy in Python

The state pattern

A state example

State versus strategy

State transition as coroutines

The singleton pattern

Singleton implementation

Module variables can mimic singletons

The template pattern

A template example

Exercises

Summary

11. Python Design Patterns II

The adapter pattern

The facade pattern

The flyweight pattern

The command pattern

The abstract factory pattern

The composite pattern

Exercises

Summary

12. Testing Object-Oriented Programs

Why test?

Test-driven development

Unit testing

Assertion methods

Reducing boilerplate and cleaning up

Organizing and running tests

Ignoring broken tests

Testing with pytest

One way to do setup and cleanup

A completely different way to set up variables

Skipping tests with pytest

Imitating expensive objects

How much testing is enough?

Case study

Implementing it

Exercises

Summary

13. Concurrency

Threads

The many problems with threads

Shared memory

The global interpreter lock

Thread overhead

Multiprocessing

Multiprocessing pools

Queues

The problems with multiprocessing Futures

AsyncIO

AsyncIO in action

Reading an AsyncIO Future

AsyncIO for networking

Using executors to wrap blocking code

Streams

Executors

AsyncIO clients

Case study

Exercises

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

This book introduces the terminology of the object-oriented paradigm. It focuses on object-oriented design with step-by-step examples. It guides us from simple inheritance, one of the most useful tools in the object-oriented programmer's toolbox, through exception handling to design patterns, an object-oriented way of looking at object-oriented concepts.

Along the way, we'll learn how to integrate the object-oriented and the not-so-object-oriented aspects of the Python programming language. We will learn the complexities of string and file manipulation, emphasizing the difference between binary and textual data.

We'll then cover the joys of unit testing, using not one, but two unit testing frameworks. Finally, we'll explore, through Python's various concurrency paradigms, how to make objects work well together at the same time.

Each chapter includes relevant examples and a case study that collects the chapter's contents into a working (if not complete) program.

Who this book is for

This book specifically targets people who are new to object-oriented programming. It assumes you have basic Python skills. You'll learn object-oriented principles in depth. It is particularly useful for system administrators who have used Python as a gluelanguage and would like to improve their programming skills.

Alternatively, if you are familiar with object-oriented programming in other languages, then this book will help you understand the idiomatic ways to apply your knowledge in the Python ecosystem.

What this book covers

This book is loosely divided into four major parts. In the first four chapters, we will dive into the formal principles of object-oriented programming and how Python leverages them. In Chapter 5, Whento UseObject-OrientedProgramming, through Chapter 8, Stringsand Serialization, we will cover some of Python's idiosyncratic applications of these principles by learning how they are applied to a variety of Python's built-in functions. Chapter 9, TheIteratorPattern, through Chapter 11, PythonDesignPatternsII, cover design patterns, and the final two chapters discuss two bonus topics related to Python programming that may be of interest.

Chapter 1, Object-OrientedDesign, covers important object-oriented concepts. It deals mainly with terminology such as abstraction, classes, encapsulation, and inheritance. We also briefly look at UML to model our classes and objects.

Chapter 2, ObjectsinPython, discusses classes and objects as they are used in Python. We will learn about attributes and behaviors of Python objects, and the organization of classes into packages and modules. Lastly, we will see how to protect our data.

Chapter 3, WhenObjectsAreAlike, gives us a more in-depth look into inheritance. It covers multiple inheritance and shows us how to extend built-in. This chapter also covers how polymorphism and duck typing work in Python.

Chapter 4, ExpectingtheUnexpected, looks into exceptions and exception handling. We will learn how to create our own exceptions and how to use exceptions for program flow control.

Chapter 5, WhentoUseObject-OrientedProgramming, deals with creating and using objects. We will see how to wrap data using

properties and restrict data access. This chapter also discusses the DRY principle and how not to repeat code.

Chapter 6, PythonDataStructures, covers the object-oriented features of Python's built-in classes. We'll cover tuples, dictionaries, lists, and sets, as well as a few more advanced collections. We'll also see how to extend these standard objects.

Chapter 7, PythonObject-OrientedShortcuts, as the name suggests, deals with time-savers in Python. We will look at many useful built-in functions, such as method overloading using default arguments. We'll also see that functions themselves are objects and how this is useful.

Chapter 8, StringsandSerialization, looks at strings, files, and formatting. We'll discuss the difference between strings, bytes, and byte arrays, as well as various ways to serialize textual, object, and binary data to several canonical representations.

Chapter 9, TheIteratorPattern, introduces the concept of design patterns and covers Python's iconic implementation of the iterator pattern. We'll learn about list, set, and dictionary comprehensions. We'll also demystify generators and coroutines.

Chapter 10, PythonDesignPatternsI, covers several design patterns, including the decorator, observer, strategy, state, singleton, and template patterns. Each pattern is discussed with suitable examples and programs implemented in Python.

Chapter 11, PythonDesignPatternsII, wraps up our discussion of design patterns with coverage of the adapter, facade, flyweight, command, abstract, and composite patterns. More examples of how idiomatic Python code differs from canonical implementations are provided.

Chapter 12, TestingObject-OrientedPrograms, opens with why testing is so important in Python applications. It focuses on test-driven

development and introduces two different testing suites: unittest and py.test. Finally, it discusses mocking test objects and code coverage.

Chapter 13, Concurrency, is a whirlwind tour of Python's support (and lack thereof) of concurrency patterns. It discusses threads, multiprocessing, futures, and the modern AsyncIO library.

To get the most out of this book

All the examples in this book rely on the Python 3 interpreter. Make sure you are not using Python 2.7 or earlier. At the time of writing, Python 3.7 was the latest release of Python. Many examples will work on earlier revisions of Python 3, but you'll likely experience a lot of frustration if you're using anything older than 3.5.

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. You'll probably want to have one of these for extracurricular research and debugging anyway!

In addition, some of the examples in this book rely on third-party libraries that do not ship with Python. They are introduced within the book at the time they are used, so you do not need to install them in advance.

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

1. Log in or register at www.packt.com.

2. Select the SUPPORT tab.

3. Click on Code Downloads & Errata.

4. Enter the name of the book in the Search box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder 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 book is also hosted on GitHub at https://githu b.com/PacktPublishing/Python-3-Object-Oriented-Programming-Third-Edition. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."

A block of code is set as follows:

class Point: def init (self, x=0, y=0): self.move(x, y)

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

import database

db = database Database()

# Do queries on db

Any command-line input or output is written as follows:

>>> print(secret string SecretString plain string)

ACME: Top Secret

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Most object-oriented programming languages have the concept of a constructor."

Warningsorimportantnotesappearlikethis.

Tipsandtricksappearlikethis.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email feedback@packtpub.com and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at questions@packtpub.com.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packt.com with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.