Preface

The Python programming language is extremely popular and used for a variety of applications. The Python language is designed to make it relatively easy to create small programs. To create more sophisticated software, we need to acquire a number of important programming and software design skills.

This book describes the object-oriented approach to creating programs in Python. It introduces the terminology of object-oriented programming, demonstrating software design and Python programming through step-by-step examples. It describes how to make use of inheritance and composition to build software from individual elements. It shows how to use Python's built-in exceptions and data structures, as well as elements of the Python standard library. A number of common design patterns are described with detailed examples.

This book covers how to write automated tests to confirm that our software works. It also shows how to use the various concurrency libraries available as part of Python; this lets us write software that can make use of multiple cores and multiple processors in a modern computer. An extended case study covers a simple machine learning example, showing a number of alternative solutions to a moderately complicated problem.

Who this book is for

This book targets people who are new to object-oriented programming in Python. It assumes basic Python skills. For readers with a background in another object-oriented programming language, this book will expose many distinctive features of Python's approach.

Because of Python's use for data science and data analytics, this book touches on the related math and statistics concepts. Some knowledge in these areas can help to make the applications of the concepts more concrete.

What this book covers

This book is divided into four overall sections. The first six chapters provide the core principles and concepts of object-oriented programming and how these are implemented in Python. The next three chapters take a close look at Python built-in features through the lens of object-oriented programming. Chapters 10, 11, and 12 look at a number of common design patterns and how these can be handled in Python. The final section covers two additional topics: testing and concurrency.

Chapter 1, Object-Oriented Design, introduces the core concepts underlying object-oriented design. This provides a road map through the ideas of state and behavior, attributes and methods, and how objects are grouped into classes. This chapter also looks an encapsulation, inheritance, and composition. The case study for this chapter introduces the machine learning problem, which is an implementation of a k-nearest neighbors (k-NN) classifier.

Chapter 2, Objects in Python, shows how class definitions work in Python. This will include the type annotations, called type hints, class definitions, modules, and packages. We'll talk about practical considerations for class definition and encapsulation. The case study will begin to implement some of the classes for the k-NN classifier.

Chapter 3, When Objects Are Alike, addresses how classes are related to each other. This will include how to make use of inheritance and multiple inheritance. We'll look at the concept of polymorphism among the classes in a class hierarchy. The case study will look at alternative designs for the distance computations used to find the nearest neighbors.

Chapter 4, Expecting the Unexpected, looks closely at Python's exceptions and exception handling. We'll look at the built-in exception hierarchy. We'll also look at how unique exceptions can be defined to reflect a unique problem domain or application. In the case study, we'll apply exceptions to data validation.

Chapter 5, When to Use Object-Oriented Programming, dives more deeply into design techniques. This chapter will look at how attributes can be implemented via Python's properties. We'll also look at the general concept of a manager for working with collections of objects. The case study will apply these ideas to expand on the k-NN classifier implementation.

Chapter 6, Abstract Base Classes and Operator Overloading, is a deep dive into the idea of abstraction, and how Python supports abstract base classes. This will involve comparing duck typing with more formal methods of Protocol definition. It will include the techniques for overloading Python's built-in operators. It will also look at metaclasses and how these can be used to modify class construction. The case study will redefine some of the existing classes to show how abstraction must be used carefully to lead to simplification of a design.

Chapter 7, Python Data Structures, examines a number of Python's built-in collections. This chapter examines tuples, dictionaries, lists, and sets. It also looks at how dataclasses and named tuples can simplify a design by providing a number of common features of a class. The case study will revise some earlier class definitions to make use of these new techniques.

Chapter 8, The Intersection of Object-Oriented and Functional Programming, looks at Python constructs that aren't simply class definitions. While all of Python is object-oriented, function definitions allow us to create callable objects without the clutter of a class definition. We'll also look at Python's context manager construct and the with statement. In the case study, we'll look at alternative designs that avoid some class clutter.

Chapter 9, Strings, Serialization, and File Paths, covers the way objects are serialized as strings and how strings can be parsed to create objects. We'll look at several physical formats, including Pickle, JSON, and CSV. The case study will revisit how sample data is loaded and processed by the k-NN classifier.

Chapter 10, The Iterator Pattern, describes the ubiquitous concept of iteration in Python. All of the built-in collections are iterable, and this design pattern is central to a great deal of how Python works. We'll look at Python comprehensions and generator functions, also. The case study will revisit some earlier designs using generator expressions and list comprehensions to partition samples for testing and training.

Chapter 11, Common Design Patterns, looks at some common object-oriented design. This will include the Decorator, Observer, Strategy, Command, State, and Singleton design patterns.

Chapter 12, Advanced Design Patterns, looks at some more advanced object-oriented design. This will include the Adapter, Façade, Flyweight, Abstract Factory, Composite, and Template patterns.

Chapter 13, Testing Object-Oriented Programs, shows how to use unittest and pytest to provide an automated unit test suite for a Python application. This will look at some more advanced testing techniques, like using mock objects to isolate the unit under test. The case study will show how to create test cases for the distance computations covered in Chapter 3.

Chapter 14, Concurrency, looks at how we can make use of multi-core and multi-processor computer systems to do computations rapidly and write software that is responsive to external events. We'll look at threads and multiprocessing, as well as Python's asyncio module. The case study will show how to use these techniques to do hyperparameter tuning on the k-NN model.

To get the most out of this book

All of the examples were tested with Python 3.9.5. The mypy tool, version 0.812, was used to confirm that the type hints were consistent.

Some of the examples depend on an internet connection to gather data. These interactions with websites generally involve small downloads.

Some of the examples involve packages that are not part of Python's built-in standard library. In the relevant chapters, we note the packages and provide the install instructions. All of these extra packages are in the Python Package Index, at https://pypi.org.

Download the example code files

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Python-Object-Oriented-Programming---4th-edition.

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

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781801077262_ColorImages.pdf

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. For example: "You can confirm Python is running by importing the antigravity module at the >>> prompt."

A block of code is set as follows:

class Fizz:
    def member(self, v: int) -> bool:
        return v % 5 == 0

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

class Fizz:
    def member(self, v: int) -> bool:
        return v % 5 == 0

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

python -m pip install tox

Bold: Indicates a new term, an important word, or words that you see on the screen, for example, in menus or dialog boxes. For example: "Formally, an object is a collection of data and associated behaviors."

Warnings or important notes appear like this.

Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected], and mention the book's title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

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 http://www.packtpub.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 [email protected] 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 http://authors.packtpub.com.

Share Your Thoughts

Once you've read Python Object-Oriented Programming, Fourth Edition, we'd love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we're delivering excellent quality content.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.238.71.155