Hour 14. Exploring the World of Object-Oriented
Programming
What You’ll Learn in This Hour:
How to create object classes
Defining attributes and methods in classes
How to use classes in your Python scripts
How to use class modules in your Python scripts
So far, all the Python scripts presented in this book have followed the procedural style of
programming. With procedural programming, you create variables and functions within your code to
perform certain procedures, such as storing values in variables and then checking them with
structured statements. The data that you use and the functions you create are completely separate
entities, with no specific relationship to one another. With object-oriented programming, on the
other hand, variables and functions are grouped into common objects that you can use in any program.
In this hour, you’ll see just what object-oriented programming is and how to use it in your Python
scripts.
Understanding the Basics of Object-Oriented Programming
Before you can start working on object-oriented programming (commonly called OOP), you need to
know how it works. OOP uses a completely different paradigm than the coding you’ve been doing so
far in this book. OOP requires that you think differently about how your programs work and how you
code them.
What Is OOP?
With OOP, everything is related to objects. (I guess that’s why they call it object-oriented!) Objects
are the data you use in your applications, grouped together into a single entity.
For example, if you’re writing a program that uses cars, you can create a car object that contains
information on the car’s weight, size, engine, and number of doors. If you’re writing a program that
tracks people, you might create a person object that contains information on each person’s name,
height, age, weight, and gender.
OOP uses classes to define objects. A class is the written definition in the program code that contains
all the characteristics of the object, using variables and functions. The benefit of OOP is that once you
create a class for an object, you can use that same class any time in any other application. Just plug in
the class definition code and put it to use.
An OOP class has members, and there are two types of members:
Attributes—Class attributes denote features of an object (such as the weight, engine, and
number of doors of a car). A class can contain many attributes, with each attribute describing a
different feature of the object.
Methods—Methods are similar to the standard Python functions that you’ve been using. A