Chapter 15. Classes and Methods
Python is an object-oriented language—that is, it provides features that support object-oriented programming, which has these defining characteristics:
-
Most of the computation is expressed in terms of operations on objects.
-
Objects often represent things in the real world, and methods often correspond to the ways things in the real world interact.
-
Programs include class and method definitions.
For example, in the previous chapter we defined a Time
class that corresponds to the way people record the time of day, and we defined functions that correspond to the kinds of things people do with times. But there was no explicit connection between the definition of the Time
class and the function definitions that follow. We can make the connection explicit by rewriting a function as a method, which is defined inside a class definition.
Defining Methods
In the previous chapter, we defined a class named Time
and wrote a function named print_time
that displays a time of day:
class
Time
:
"""Represents the time of day."""
def
print_time
(
time
):
s
=
f
'
{
time
.
hour
:
02d
}
:
{
time
.
minute
:
02d
}
:
{
time
.
second
:
02d
}
'
(
s
)
To make print_time
a method, all we have to do is move the function definition inside the class definition. Notice the change in indentation.
At the same time, we’ll change the name of the parameter from time
to self
. This change is not necessary, but it is conventional for the first parameter of a method to be named self
:
class
Time
:
"""Represents ...
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.