Chapter 6. Oh Oh: Objects and Classes

No object is mysterious. The mystery is your eye.

Elizabeth Bowen

Take an object. Do something to it. Do something else to it.

Jasper Johns

Up to this point, you’ve seen data structures such as strings and dictionaries, and code structures such as functions and modules. In this chapter, you’ll deal with custom data structures: objects.

What Are Objects?

As I mention in Chapter 2, everything in Python, from numbers to modules, is an object. However, Python hides most of the object machinery by means of special syntax. You can type num = 7 to create a object of type integer with the value 7, and assign an object reference to the name num. The only time you need to look inside objects is when you want to make your own or modify the behavior of existing objects. You’ll see how to do both in this chapter.

An object contains both data (variables, called attributes) and code (functions, called methods). It represents a unique instance of some concrete thing. For example, the integer object with the value 7 is an object that facilitates methods such as addition and multiplication, as is demonstrated in “Numbers”. 8 is a different object. This means there’s an Integer class in Python, to which both 7 and 8 belong. The strings 'cat' and 'duck' are also objects in Python, and have string methods that you’ve seen, such as capitalize() and replace().

When you create new objects no one has ever created before, you must create a class that indicates ...

Get Introducing Python now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.