文档介绍:PART VI
Classes and OOP
Download at
Download at
CHAPTER 25
OOP: The Big Picture
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 par-
ticipate 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 any-
thing we’ve seen so far.
One note up front: in Python, OOP is entirely optional, and you don’t need to use
classes just to get started. In fact, you can get plenty of work done with simpler con-
structs such as functions, or even simple top-level script code. Because using classes
well requires some up-front planning, they tend to be of more interest to people who
work in strategic mode (doing long-term product development) than to people who
work in tactical mode (wher