Section 1.5 introduced the basic terminology and concepts of object-oriented programming. Everything in Python is an object, so you’ve been using objects constantly throughout this book. Just as houses are built from blueprints, objects are built from classes—one of the core technologies of object-oriented programming. Building a new object from even a large class is simple—you typically write one statement.
You’ve already used lots of classes created by other people. In this chapter you’ll learn how to create your own custom classes. You’ll focus on “crafting valuable classes” that help you meet the requirements of the applications you’ll build. You’ll use object-oriented programming with its core technologies of classes, objects, inheritance and polymorphism. Software applications are becoming larger and more richly functional. Object-oriented programming makes it easier for you to design, implement, test, debug and update such edge-of-the-practice applications. Read Sections 10.1 through 10.9 for a code-intensive introduction to these technologies. Most people can skip Sections 10.10 through 10.15, which provide additional perspectives on these technologies and present additional related features.
The vast majority of object-oriented programming you’ll do in Python is object-based programming in which you primarily create and use objects of existing classes. You’ve been doing this throughout the book with built-in types like int
, float
, str
, list
, tuple
, dict
and set
, with Python Standard Library types like Decimal
, and with NumPy array
s, Matplotlib Figure
s and Axes
, and pandas Series
and DataFrame
s.
To take maximum advantage of Python you must familiarize yourself with lots of preexisting classes. Over the years, the Python open-source community has crafted an enormous number of valuable classes and packaged them into class libraries. This makes it easy for you to reuse existing classes rather than “reinventing the wheel.” Widely used open-source library classes are more likely to be thoroughly tested, bug free, performance tuned and portable across a wide range of devices, operating systems and Python versions. You’ll find abundant Python libraries on the Internet at sites like GitHub, BitBucket, SourceForge and more—most easily installed with conda
or pip
. This is a key reason for Python’s popularity. The vast majority of the classes you’ll need are likely to be freely available in open-source libraries.
Classes are new data types. Each Python Standard Library class and third-party library class is a custom type built by someone else. In this chapter, you’ll develop application-specific classes, like CommissionEmployee
, Time
, Card
, DeckOfCards
and more. The dozens of chapter exercises challenge you to create additional classes for a wide variety of applications.
Most applications you’ll build for your own use will commonly use either no custom classes or just a few. If you become part of a development team in industry, you may work on applications that contain hundreds, or even thousands, of classes. You can contribute your custom classes to the Python open-source community, but you are not obligated to do so. Organizations often have policies and procedures related to open-sourcing code.
Perhaps most exciting is the notion that new classes can be formed through inheritance and composition from classes in abundant class libraries. Eventually, software will be constructed predominantly from standardized, reusable components just as hardware is constructed from interchangeable parts today. This will help meet the challenges of developing ever more powerful software.
When creating a new class, instead of writing all new code, you can designate that the new class is to be formed initially by inheriting the attributes (variables) and methods (the class version of functions) of a previously defined base class (also called a superclass). The new class is called a derived class (or subclass). After inheriting, you then customize the derived class to meet the specific needs of your application. To minimize the customization effort, you should always try to inherit from the base class that’s closest to your needs. To do that effectively, you should familiarize yourself with the class libraries that are geared to the kinds of applications you’ll be building.
We explain and demonstrate polymorphism, which enables you to conveniently program “in the general” rather than “in the specific.” You simply send the same method call to objects possibly of many different types. Each object responds by “doing the right thing.” So the same method call takes on “many forms,” hence the term “poly-morphism.” We’ll explain how to implement polymorphism through inheritance and a Python feature called duck typing. We’ll explain both and show examples of each.
You’ve already used a random-numbers-based die-rolling simulation and used those techniques to implement the popular dice game craps. Here, we present a card-shuffling-and-dealing simulation, which you can use to implement your favorite card games. You’ll use Matplotlib with attractive public-domain card images to display the full deck of cards both before and after the deck is shuffled. In the exercises, you can implement the popular card games blackjack and solitaire, and evaluate a five-card poker hand.
Python 3.7’s new data classes help you build classes faster by using a more concise notation and by autogenerating portions of the classes. The Python community’s early reaction to data classes has been positive. As with any major new feature, it may take time before it’s widely used. We present class development with both the older and newer technologies.
Other concepts you’ll learn include:
How to specify that certain identifiers should be used only inside a class and not be accessible to clients of the class.
Special methods for creating string representations of your classes’ objects and specifying how objects of your classes work with Python’s built-in operators (a process called operator overloading).
An introduction to the Python exception class hierarchy and creating custom exception classes.
Testing code with the Python Standard Library’s doctest
module.
How Python uses namespaces to determine the scopes of identifiers.