Chapter 6. Classes
This chapter explores the Python class—a device used to
implement new kinds of objects in Python. Classes are Python’s
main object-oriented programming (OOP) tool, so we’ll also look
at OOP basics along the way in this chapter. In Python, classes are
created with a new statement we’ll meet here too: the
class
statement. As we’ll see, objects
defined with classes can look a lot like the built-in types we saw
earlier in the book.
One note up front: 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 constructs such as functions. But classes turn out to be one of the most useful tools Python provides, and we hope to show you why here. They’re also employed in popular Python tools like the Tkinter GUI API, so most Python programmers will usually find at least a working knowledge of class basics helpful.
Why Use Classes?
Remember when we told you that programs do things with stuff? In simple terms, classes are just a way to define new sorts of stuff, which reflect real objects in your program’s domain. For instance, suppose we’ve decided to implement that hypothetical pizza-making robot we used as an example in Chapter 4. If we implement it using classes, we can model more of its real-world structure and relationships:
- Inheritance
Pizza-making robots are a kind of robot, and so posses the usual robot-y properties. In OOP terms, we say they inherit properties from the general category ...
Get Learning Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.