Chapter 14. Classes and Functions
At this point you know how to use functions to organize code and how to use built-in types to organize data. The next step is object-oriented programming (OOP), which uses programmer-defined types to organize both code and data.
Object-oriented programming is a big topic, so we will proceed gradually. In this chapter, we’ll start with code that is not idiomatic—that is, it is not the kind of code experienced programmers write—but it is a good place to start. In the next two chapters, we will use additional features to write more idiomatic code.
Programmer-Defined Types
We have used many of Python’s built-in types—now we will define a new type. As a first example, we’ll create a type called Time
that represents a time of day. A programmer-defined type is also called a class. A class definition looks like this:
class
Time
:
"""Represents a time of day."""
The header indicates that the new class is called Time
. The body is a docstring that explains what the class is for. Defining a class creates a class object.
The class object is like a factory for creating objects. To create a Time
object, you call Time
as if it were a function:
lunch
=
Time
()
The result is a new object whose type is __main__.Time
, where __main__
is the name of the module where Time
is defined:
type
(
lunch
)
__main__.Time
When you print an object, Python tells you what type it is and where it is stored in memory (the prefix 0x
means that the following number is in hexadecimal): ...
Get Think Python, 3rd Edition 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.