Chapter 15. Classes and Objects

At this point you know how to use functions to organize code and built-in types to organize data. The next step is to learn “object-oriented programming”, which uses programmer-defined types to organize both code and data. Object-oriented programming is a big topic; it will take a few chapters to get there.

Code examples from this chapter are available from http://thinkpython2.com/code/Point1.py; solutions to the exercises are available from http://thinkpython2.com/code/Point1_soln.py.

Programmer-Defined Types

We have used many of Python’s built-in types; now we are going to define a new type. As an example, we will create a type called Point that represents a point in two-dimensional space.

In mathematical notation, points are often written in parentheses with a comma separating the coordinates. For example, (0,0) represents the origin, and (x,y) represents the point x units to the right and y units up from the origin.

There are several ways we might represent points in Python:

  • We could store the coordinates separately in two variables, x and y.

  • We could store the coordinates as elements in a list or tuple.

  • We could create a new type to represent points as objects.

Creating a new type is more complicated than the other options, but it has advantages that will be apparent soon.

A programmer-defined type is also called a class. A class definition looks like this:

class Point:
    """Represents a point in 2-D space."""

The header indicates that the new class ...

Get Think Python, 2nd Edition now with O’Reilly online learning.

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