User Guide

144
6.6 Classes and Objects
Python is an object-oriented language. Object-oriented
programming (OOP) is a way of writing code that treats data and
concepts as standalone objects. These objects can contain
multiple items of data (“fields”), and even functions that operate
on that data (“methods”).
There are several benefits to OOP:
• It is easier to reuse code in other projects.
• It breaks large projects down into smaller, more-
manageable chunks.
• Certain types of information are well-suited to being
represented as objects.
• Objects can “inherit” fields and methods from other
objects.
As a simple example, consider an entry in your phone’s address
book or contact list. You can think of each entry as an object, and
inside each object there are numerous fields. “First name” is one
field, “Last name” is another, and so on.
Introducing Classes
In Python, a class is like a blueprint. It describes the structure of
objects and defines their methods. To use an object, you need
to create an instance of the class that describes it.
You create your own classes in Python by using the class
keyword. For example:
class AddressBookEntry:
firstname = ""
lastname = ""
telephone = ""
To create an instance of that class and get a usable object:
Alice = AddressBookEntry()