Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Mastering Object-Oriented Python
Mastering Object-Oriented Python

Mastering Object-Oriented Python: Build powerful applications with reusable code using OOP design patterns and Python 3.7 , Second Edition

Arrow left icon
Profile Icon Steven F. Lott
Arrow right icon
$12.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8 (4 Ratings)
Paperback Jun 2019 770 pages 2nd Edition
eBook
$29.99
Paperback
$43.99
Subscription
Free Trial
Renews at $12.99p/m
Arrow left icon
Profile Icon Steven F. Lott
Arrow right icon
$12.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8 (4 Ratings)
Paperback Jun 2019 770 pages 2nd Edition
eBook
$29.99
Paperback
$43.99
Subscription
Free Trial
Renews at $12.99p/m
eBook
$29.99
Paperback
$43.99
Subscription
Free Trial
Renews at $12.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $15.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Mastering Object-Oriented Python

Preliminaries, Tools, and Techniques

To make the design issues in the balance of the book more clear, we need to look at some the problems that serve as motivation. One of these is using object-oriented programming (OOP) for simulation. Simulation was one of the early problem domains for OOP. This is an area where OOP works out particularly elegantly.

We've chosen a problem domain that's relatively simple: the strategies for playing the game of blackjack. We don't want to endorse gambling; indeed, a bit of study will show that the game is stacked heavily against the player. This should reveal that most casino gambling is little more than a tax on the innumerate.

The first section of this chapter will review the rules of the game of Blackjack. After looking at the card game, the bulk of this chapter will provide some background in tools that are essential for writing complete Python programs and packages. We'll look at the following concepts:

  • The Python runtime environment and how the special method names implement the language features
  • Integrated Development Environments (IDEs)
  • Using the pylint or black tools to create a uniform style
  • Using type hints and the mypy tool to establish proper use of functions, classes, and variables
  • Using timeit for performance testing
  • Using unittest, doctest, and pytest for unit testing
  • Using sphinx and RST-based markup to create usable documentation

While some of these tools are part of the Python standard library, most of them are outside the library. We'll discuss installation of tools when we talk about the Python runtime in general.

This book will try to avoid digressing into the foundations of Python OOP. We're assuming that you've already read Packt's Python3 Object-Oriented Programming. We don't want to repeat things that are nicely stated elsewhere. We will focus on Python 3.

We'll refer to a number of common object-oriented design patterns and will try to avoid repeating the presentation in Packt's Learning Python Design Patterns.

We'll cover the following topics in this chapter:

  • About the Blackjack game
  • The Python runtime and special methods
  • Interaction, scripting and tools
  • Selecting an IDE
  • Consistency and style
  • Type hints and the mypy program
  • Performance – the timeit module
  • Testing  unittest and doctest
  • Documentation  sphinx and RST markup
  • Installing components

Technical requirements

About the Blackjack game

Many of the examples in the book will center on simulations of a process with a number of moderately complex state changes. The card game of Blackjack involves a few rules and a few state changes during play. If you're unfamiliar with the game of Blackjack, here's an overview.

The objective of the game is to accept cards from the dealer to create a hand that has a point total that is between the dealer's total and twenty-one. The dealer's hand is only partially revealed, forcing the player to make a decision without knowing the dealer's total or the subsequent cards from the deck.

The number cards (2 to 10) have point values equal to the number. The face cards (Jack, Queen, and King) are worth 10 points. The Ace is worth either eleven points or one point. When using an ace as eleven points, the value of the hand is soft. When using an ace as one point, the value is hard.

A hand with an Ace and a seven, therefore, has a hard total of eight and a soft total of 18. This leads the player to choose to take extra cards. If the dealer is showing a face card, it's very likely the dealer is holding twenty points, and the player may not want to risk taking another card.

Each suit has four two-card combinations that total 21. These are all called Blackjack, even though only one of the four combinations involves a Jack. These combinations often provide a bonus payout, because there are only four of them available.

Most of the game is about proper choice of cards. There is, of course, a betting element. The distinction between playing and betting is made somewhat more complicated by the provision to split one hand into two hands. This is allowed when the player's two cards have the same rank. This option will be detailed in the next section on how the game is played.

Playing the game

The mechanics of play generally work as follows. The details can vary, but the outline is similar:

  • First, the player and dealer each get two cards. The player, of course, knows the value of both of their cards. They're dealt face up in a casino.
  • One of the dealer's cards is revealed to the player. It's displayed face up. The player, therefore, knows a little bit about the dealer's hand, but not everything. This is typical of more complex simulations where partial information is available and statistical modeling is required to make appropriate decisions.
  • If the dealer has an Ace showing, the player is offered the opportunity to place an additional insurance bet. This is a special case, and is typical of more complex simulations where there are exceptions.
  • For the balance of the game, the player can elect to receive cards, or stop receiving cards. There are four choices available:
    • The player can hit, which means take another card.
    • They player can or stand or stand pat with the cards dealt.
    • If the player's cards match, the hand can be split. This entails an additional bet, and the two hands are played separately. 
    • The player can double their bet before taking one last card. This is called doubling down.

The final evaluation of the hand works as follows:

  • If the player went over 21, the hand is a bust, the player loses, and the dealer's face-down card is irrelevant. This provides an advantage to the dealer.
  • If the player's total is 21 or under, then the dealer takes cards according to a simple, fixed rule. The dealer must hit a hand that totals less than 18; the dealer must stand on a hand that totals 18 or more.
  • If the dealer goes bust, the player wins.
  • If both the dealer and player are 21 or under, the hands are compared. The higher total is the winner. In the event of a tie, the game is a push, neither a win nor a loss. If the player wins with 21, they win a larger payout, usually 1.5 times the bet.

The rules can vary quite a bit. We'll elide these details to focus on the Python code required for simulation.

Blackjack player strategies

In the case of blackjack, there are actually two kinds of strategies that the player must use:

  • A strategy for deciding what play to make: take insurance, hit, stand, split, or double down.
  • A strategy for deciding what amount to bet. A common statistical fallacy leads players to raise and lower their bets in an attempt to preserve their winnings and minimize their losses. These are interesting, stateful algorithms in spite of the underlying fallacies.

These two sets of strategies are, of course, prime examples of the Strategy design pattern.

Object design for simulating Blackjack

We'll use elements of the game, such as the player, hand, and card, as examples for object modeling. We won't design the entire simulation. We'll focus on elements of this game because they have some nuance, but aren't terribly complex.

The cards are relatively simple, immutable objects. There are a variety of modeling techniques available. Cards fall into a simple class hierarchy of the number cards, face cards, and the Ace.  There are simple containers, including hands of card instances, and decks of cards as well. These are stateful collections with cards being added and removed. There are a number of ways to implement this in Python and we'll look at many alternatives. We also need to look at the player as a whole. A player will have a sequence of hands, as well as a betting strategy and a Blackjack play strategy. This is a rather complex composite object.

The Python runtime and special methods

One of the essential concepts for mastering object-oriented Python is to understand how object methods are implemented. Let's look at a relatively simple Python interaction:

>>> f = [1, 1, 2, 3]
>>> f += [f[-1] + f[-2]]
>>> f
[1, 1, 2, 3, 5]

We've created a list, f, with a sequence of values. We then mutated this list using the += operator to append a new value. The f[-1] + f[-2] expression computes the new value to be appended.

The value of f[-1] is implemented using the list object's __getitem__() method. This is a core pattern of Python: the simple operator-like syntax is implemented by special methods. The special methods have names surrounded with __ to make them distinctive. For simple prefix and suffix syntax, the object is obvious; f[-1] is implemented as f.__getitem__(-1).

The additional operation is similarly implemented by the __add__() special method. In the case of a binary operator, Python will try both operands to see which one offers the special method. In this example, both operands are integers, and both will provide a suitable implementation. In the case of mixed types, the implementation of the binary operator may coerce one value into another type. f[-1] + f[-2], then, is implemented as f.__getitem__(-1).__add__(f.__getitem__(-2)).

The update of f by the += operator is implemented by the __iadd__() special method. Consequently, f += [x] is implemented as f.__iadd__([x]).

Throughout the first eight chapters, we'll look very closely at these special methods and how we can design our classes to integrate very tightly with Python's built-in language features. Mastering the special methods is the essence of mastering object-oriented Python.

Interaction, scripting, and tools

Python is often described as Batteries Included programming. Everything required is available directly as part of a single download. This provides the runtime, the standard library, and the IDLE editor as a simple development environment.

It's very easy to download and install Python 3.7 and start running it interactively on the desktop. The example in the previous section included the >>> prompt from interactive Python. 

If you're using the Iron Python (IPython) implementation, the interaction will look like this:

In [1]: f = [1, 1, 2, 3]
In [3]: f += [f[-1] + f[-2]]
In [4]: f
Out[4]: [1, 1, 2, 3, 5]

The prompt is slightly different, but the language is the same. Each statement is evaluated as it is presented to Python. 

This is handy for some experimentation. Our goal is to build tools, frameworks, and applications. While many of the examples will be shown in an interactive style, most of the actual programming will be via script files.

Running examples interactively makes a profound statement. Well-written Python code should be simple enough that it can be run from the command line.

Good Python is simple. We should be able to demonstrate a design at the >>> prompt.

Interactive use is not our goal. Exercising code from the >>> prompt is a quality test for complexity. If the code is too complex to exercise it from the >>> prompt, then refactoring is needed.

The focus of this book is on creating complete scripts, modules, packages, and applications. Even though some examples are shown in interactive mode, the objective is to create Python files. These files may be as simple as a script or as complex as a directory with files to create a web application.

Tools such as mypy, pytest, and pylint work with Python files. Preparing script files can be done with almost any text editor. It's best, however, to work with an IDE, where a number of tools can be provided to help develop applications and scripts.

Selecting an IDE

A common question is, "What is the best IDE for doing Python development?" The short answer to this question is that the IDE choice doesn't matter very much. The number of development environments that support Python is vast and they are all very easy to use. The long answer requires a conversation about what attributes would rank an IDE as being the best.

The Spyder IDE is part of the Anaconda distribution. This makes it readily accessible to developers who've downloaded Anaconda. The IDLE editor is part of the Python distribution, and provides a simple environment for using Python and building scripts. PyCharm has a commercial license as well as a community edition, it provides a large number of features, and was used to prepare all the examples in this book.

The author makes use of having both an editor, an integrated Python prompt, and unit test results all readily available. PyCharm works well with the conda environments, avoiding confusion over what packages are installed. 

A search on the internet will provide a long list of other tools. See the IDE Python wiki page for numerous alternatives (https://wiki.python.org/moin/IntegratedDevelopmentEnvironments).

Consistency and style

All of the examples in the book were prepared using the black tool to provide consistent formatting. Some additional manual adjustments were made to keep code within the narrow sizes of printed material.

A common alternative to using black is to use pylint to identify formatting problems. These can then be corrected. In addition to detailed analysis of code quality, the pylint tool offers a numeric quality score. For this book, some pylint rules needed to be disabled. For example, the modules often have imports that are not in the preferred order; some modules also have imports that are relevant to doctest examples, and appear to be unused; some examples use global variables; and some class definitions are mere skeletons without appropriate method definitions. 

Using pylint to locate potential problems is essential. It's often helpful to silence pylint warnings. In the following example, we need to silence a pylint warning about the test_list variable name being invalid as a global variable:

# pylint: disable=invalid-name
test_list = """
>>> f = [1, 1, 2, 3]
>>> f += [f[-1] + f[-2]]
>>> f
[1, 1, 2, 3, 5]
"""

if __name__ == "__main__":
import doctest
__test__ = {name: value
for name, value in locals().items()
if name.startswith("test_")}
doctest.testmod(verbose=False)

Besides helping enforce a consistent style, the pylint warnings are helpful for identifying spelling mistakes and a list of common errors. For example, the instance variable is commonly self. An accidental spelling error of sefl will be found by pylint

Type hints and the mypy program

Python 3 permits the use of type hints. The hints are present in assignment statements, function, and class definitions. They're not used directly by Python when the program runs. Instead, they're used by external tools to examine the code for improper use of types, variables, and functions. Here's a simple function with type hints:

def F(n: int) -> int:
if n in (0, 1):
return 1
else:
return F(n-1) + F(n-2)

print("Good Use", F(8))
print("Bad Use", F(355/113))

When we run the mypy program, we'll see an error such as the following:

Chapter_1/ch01_ex3.py:23: error: Argument 1 to "F" has incompatible type "float"; expected "int"

This message informs us of the location of the error: the file is Chapter_1/ch01_ex3.py, which is the 23rd line of the file. The details tell us that the function, F, has an improper argument value. This kind of problem can be difficult to see. In some cases, unit tests might not cover this case very well, and it's possible for a program to harbor subtle bugs because data of an improper type might be used.

Performance – the timeit module

We'll make use of the timeit module to compare the actual performance of different object-oriented designs and Python constructs. We'll focus on the timeit() function in this module. This function creates a Timer object that's used to measure the execution of a given block of code. We can also provide some preparatory code that creates an environment. The return value from this function is the time required to run the given block of code.

The default count is 100,000. This provides a meaningful time that averages out other OS-level activity on the computer doing the measurement. For complex or long-running statements, a lower count may be prudent.

Here's a simple interaction with timeit:

>>> timeit.timeit("obj.method()", 
... """
... class SomeClass:
... def method(self):
... pass
... obj= SomeClass()
... """)
0.1980541350058047

The code to be measured is obj.method(). It is provided to timeit() as a string. The setup code block is the class definition and object construction. This code block, too, is provided as a string. It's important to note that everything required by the statement must be in the setup. This includes all imports, as well as all variable definitions and object creation.

This example showed that 100,000 method calls that do nothing costs 0.198 seconds.

Testing – unittest and doctest

Unit testing is absolutely essential.

If there's no automated test to show a particular element functionality, then the feature doesn't really exist. Put another way, it's not done until there's a test that shows that it's done.

We'll touch, tangentially, on testing. If we delved into testing each object-oriented design feature, the book would be twice as long as it is. Omitting the details of testing has the disadvantage of making good unit tests seem optional. They're emphatically not optional.

Unit testing is essential.

When in doubt, design the tests first. Fit the code to the test cases.

Python offers two built-in testing frameworks. Most applications and libraries will make use of both. One general wrapper for testing is the unittest module. In addition, many public API docstrings will have examples that can be found and used by the doctest module. Also, unittest can incorporate doctest.

The pytest tool can locate test cases and execute them. This is a very useful tool, but must be installed separately from the rest of Python.

One lofty ideal is that every class and function has at least a unit test. The important, visible classes and functions will often also have doctest. There are other lofty ideals: 100% code coverage; 100% logic path coverage, and so on.

Pragmatically, some classes don't need testing. A class that extends typing.NamedTuple, for example, doesn't really need a sophisticated unit test. It's important to test the unique features of a class you've written and not the features inherited from the standard library.

Generally, we want to develop the test cases first, and then write code that fits the test cases. The test cases formalize the API for the code. This book will reveal numerous ways to write code that has the same interface. Once we've defined an interface, there are still numerous candidate implementations that fit the interface. One set of tests will apply to several different object-oriented designs.

One general approach to using the unittest and pytest tools is to create at least three parallel directories for your project:

  • myproject: This directory is the final package that will be installed in lib/site-packages for your package or application. It has an __init__.py file. We'll put our files in here for each module.
  • tests: This directory has the test scripts. In some cases, the scripts will parallel the modules. In some cases, the scripts may be larger and more complex than the modules themselves.
  • docs: This has other documentation. We'll touch on this in the next section, as well as a chapter in part three.

In some cases, we'll want to run the same test suite on multiple candidate classes so that we can be sure each candidate works. There's no point in doing timeit comparisons on code that doesn't actually work.

Documentation – sphinx and RST markup

All Python code should have docstrings at the module, class and method level. Not every single method requires a docstring. Some method names are really well chosen, and little more needs to be said. Most times, however, documentation is essential for clarity.

Python documentation is often written using the reStructuredText (RST) markup.

Throughout the code examples in the book, however, we'll omit docstrings. The omission keeps the book to a reasonable size. This gap has the disadvantage of making docstrings seem optional. They're emphatically not optional.

This point is so important, we'll emphasize it again: docstrings are essential.

The docstring material is used three ways by Python:

  • The internal help() function displays the docstrings.
  • The doctest tool can find examples in docstrings and run them as test cases.
  • External tools, such as sphinx and pydoc, can produce elegant documentation extracts from these strings.

Because of the relative simplicity of RST, it's quite easy to write good docstrings. We'll look at documentation and the expected markup in detail in Chapter 18, Coping with the Command Line. For now, however, we'll provide a quick example of what a docstring might look like:

def factorial(n: int) -> int:
"""
Compute n! recursively.

:param n: an integer >= 0
:returns: n!

Because of Python's stack limitation, this won't
compute a value larger than about 1000!.

>>> factorial(5)
120
"""
if n == 0:
return 1
return n*factorial(n-1)

This shows the RST markup for the n parameter and the return value. It includes an additional note about limitations. It also includes a doctest example that can be used to validate the implementation using the doctest tool. The use of :param n: and :return: identifies text that will be used by the sphinx tool to provide proper formatting and indexing of the information.

Installing components

Most of the tools required must be added to the Python 3.7 environment. There are two approaches in common use:

  • Use pip to install everything.
  • Use conda to create an environment. Most of the tools described in this book are part of the Anaconda distribution.

The pip installation uses a single command:

python3 -m pip install pyyaml sqlalchemy jinja2 pytest sphinx mypy pylint black

This will install all of the required packages and tools in your current Python environment.

The conda installation creates a conda environment to keep the book's material separate from any other projects:

  1. Install conda. If you have already installed Anaconda, you have the Conda tool, nothing more needs to be done. If you don't have Anaconda yet, then install miniconda, which is the ideal way to get started. Visit https://conda.io/miniconda.html and download the appropriate version of conda for your platform.
  2. Use conda to build and activate the new environment.
  1. Then upgrade pip. This is needed because the default pip installation in the Python 3.7 environment is often slightly out of date.
  2. Finally, install black. This is required because black is not currently in any of the conda distribution channels.

Here are the commands:

$ conda create --name mastering python=3.7 pyyaml sqlalchemy jinja2 
pytest sphinx mypy pylint
$ conda activate mastering
$ python3 -m pip install --upgrade pip
$ python3 -m pip install black

The suite of tools (pytest, sphinx, mypy, pylint, and black) are essential for creating high-quality, reliable Python programs. The other components, pyyaml, sqlalchemy, and jinja2, are helpful for building useful applications.

Summary

In this chapter, we've surveyed the game of Blackjack. The rules have a moderate level of complexity, providing a framework for creating a simulation. Simulation was one of the first uses for OOP and remains a rich source of programming problems that illustrate language and library strengths.

This chapter introduces the way the Python runtime uses special methods to implement the various operators. The bulk of this book will show ways to make use of the special methods names for creating objects that interact seamlessly with other Python features.

We've also looked at a number of tools that will be required to build good Python applications. This includes the IDE, the mypy program for checking type hints, and the black and pylint programs for getting to a consistent style. We also looked at the timeit, unittest, and doctest modules for doing essential performance and functional testing. For final documentation of a project, it's helpful to install sphinx. The installation of these extra components can be done with pip or conda. The pip tool is part of Python, the conda tool requires another download to make it available.

In the next chapter, we'll start our exploration of Python with class definition. We'll focus specifically on how objects are initialized using the __init__() special method.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Extend core OOP techniques to increase integration of classes created with Python
  • Explore a variety of Python libraries for handling persistence and object serialization
  • Learn alternative approaches for solving programming problems with different attributes to address your problem domain

Description

Object-oriented programming (OOP) is a relatively complex discipline to master, and it can be difficult to see how general principles apply to each language's unique features. With the help of the latest edition of Mastering Objected-Oriented Python, you'll be shown how to effectively implement OOP in Python, and even explore Python 3.x. Complete with practical examples, the book guides you through the advanced concepts of OOP in Python, and demonstrates how you can apply them to solve complex problems in OOP. You will learn how to create high-quality Python programs by exploring design alternatives and determining which design offers the best performance. Next, you'll work through special methods for handling simple object conversions and also learn about hashing and comparison of objects. As you cover later chapters, you'll discover how essential it is to locate the best algorithms and optimal data structures for developing robust solutions to programming problems with minimal computer processing. Finally, the book will assist you in leveraging various Python features by implementing object-oriented designs in your programs. By the end of this book, you will have learned a number of alternate approaches with different attributes to confidently solve programming problems in Python.

Who is this book for?

This book is for developers who want to use Python to create efficient programs. A good understanding of Python programming is required to make the most out of this book. Knowledge of concepts related to object-oriented design patterns will also be useful.

What you will learn

  • Explore a variety of different design patterns for the __init__() method
  • Learn to use Flask to build a RESTful web service
  • Discover SOLID design patterns and principles
  • Use the features of Python 3 s abstract base
  • Create classes for your own applications
  • Design testable code using pytest and fixtures
  • Understand how to design context managers that leverage the with statement
  • Create a new type of collection using standard library and design techniques
  • Develop new number types above and beyond the built-in classes of numbers

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 14, 2019
Length: 770 pages
Edition : 2nd
Language : English
ISBN-13 : 9781789531367
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $15.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jun 14, 2019
Length: 770 pages
Edition : 2nd
Language : English
ISBN-13 : 9781789531367
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$12.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 6,500+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$129.99 billed annually
Feature tick icon Unlimited access to Packt's library of 6,500+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$179.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 6,500+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 133.97
Mastering Object-Oriented Python
$43.99
Python 3 Object-Oriented Programming
$45.99
Expert Python Programming
$43.99
Total $ 133.97 Stars icon
Banner background image

Table of Contents

20 Chapters
Preliminaries, Tools, and Techniques Chevron down icon Chevron up icon
The __init__() Method Chevron down icon Chevron up icon
Integrating Seamlessly - Basic Special Methods Chevron down icon Chevron up icon
Attribute Access, Properties, and Descriptors Chevron down icon Chevron up icon
The ABCs of Consistent Design Chevron down icon Chevron up icon
Using Callables and Contexts Chevron down icon Chevron up icon
Creating Containers and Collections Chevron down icon Chevron up icon
Creating Numbers Chevron down icon Chevron up icon
Decorators and Mixins - Cross-Cutting Aspects Chevron down icon Chevron up icon
Serializing and Saving - JSON, YAML, Pickle, CSV, and XML Chevron down icon Chevron up icon
Storing and Retrieving Objects via Shelve Chevron down icon Chevron up icon
Storing and Retrieving Objects via SQLite Chevron down icon Chevron up icon
Transmitting and Sharing Objects Chevron down icon Chevron up icon
Configuration Files and Persistence Chevron down icon Chevron up icon
Design Principles and Patterns Chevron down icon Chevron up icon
The Logging and Warning Modules Chevron down icon Chevron up icon
Designing for Testability Chevron down icon Chevron up icon
Coping with the Command Line Chevron down icon Chevron up icon
Module and Package Design Chevron down icon Chevron up icon
Quality and Documentation Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8
(4 Ratings)
5 star 50%
4 star 0%
3 star 25%
2 star 25%
1 star 0%
Daniel J. Snipes Aug 17, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I found this book to be insightful and easy to read. Steven Lott certainly has the rare talent of combing technical rigor with a certain level of playful eloquence. This is a great introduction to object oriented programming (OOP) paradigm in Python 3. This is both a useful introductory text for software engineers as well as a reference text for a more seasoned professional.
Amazon Verified review Amazon
Cesar Trejo Mar 05, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Muy buen producto 👍
Amazon Verified review Amazon
Amazon Customer Feb 27, 2023
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Pretty good text but code needs to formatted better. Most code has wraparound that makes it hard to read. Page 525 has serious formatting problem on code. However, because of the age of this edition, few are going to buy it now anyway.
Amazon Verified review Amazon
Prooffreader Feb 09, 2020
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
I get that it's useful to have an example class used throughout the book. But I think the blackjack-playing class was a little to obscure, it's not really a use case that a real programmer will come across (and gambling and games of gambling are of particularly little interest to me), and having the unicode symbols all over the place for the different suits (♠ ♥ ♣ ♦) instead of text is visually very distracting. I would have rathered follow along with a "real" program, even if its particular use case wasn't one I commonly use. A lot of references are made to the previous Python OOP book written by the author, so I bought it also even though only about 15% of it was new information to me. Despite these caveats, the author knows her stuff very well. Final note: this is a huge tome, extremely thick and difficuly to maneuver and weighs a ton.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.