So far in this book, we’ve been using the term “object” generically. Really, the code written up to this point has been object-based—we’ve passed objects around our scripts, used them in expressions, called their methods, and so on. For our code to qualify as being truly object-oriented (OO), though, our objects will generally need to also participate in something called an inheritance hierarchy.
This chapter begins our exploration of the Python class—a device used to implement new kinds of objects in Python that support inheritance. Classes are Python’s main object-oriented programming (OOP) tool, so we’ll also look at OOP basics along the way in this part of the book. OOP offers a different and often more effective way of looking at programming, in which we factor code to minimize redundancy, and write new programs by customizing existing code instead of changing it in-place.
In Python, classes are created with a new statement: the
class statement. As you’ll see, the objects
defined with classes can look a lot like the built-in types we studied
earlier in the book. In fact, classes really just apply and extend the
ideas we’ve already covered; roughly, they are packages of functions
that use and process built-in object types. Classes, though, are
designed to create and manage new objects, and they also support
inheritance—a mechanism of code customization and
reuse above and beyond anything we’ve seen so far.
One note up front: in Python, OOP is entirely ...