12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

160 Chapter 17. Classes and methods• The syntax for invoking amethod isdifferent fromthe syntax forcalling afunction.In the next few sections, we will take the functions from the previous two chapters and transformthem into methods. This transformation is purely mechanical; you can do it simply by following asequence of steps. If you are comfortable converting from one form to another, you will be able tochoose thebest form forwhatever you aredoing.17.2 PrintingobjectsIn Chapter 16, we defined a class named Time and in Exercise 16.1, you wrote a function namedprint_time:class Time(object):"""represents the time of day.attributes: hour, minute, second"""def print_time(time):print '%.2d:%.2d:%.2d' % (time.hour, time.minute, time.second)To call thisfunction, you have topass aTimeobject asan argument:>>> start = Time()>>> start.hour = 9>>> start.minute = 45>>> start.second = 00>>> print_time(start)09:45:00To make print_time a method, all we have to do is move the function definition inside the classdefinition. Notice thechange inindentation.class Time(object):def print_time(time):print '%.2d:%.2d:%.2d' % (time.hour, time.minute, time.second)Now there are two ways to call print_time. The first (and less common) way is to use functionsyntax:>>> Time.print_time(start)09:45:00Inthisuseofdotnotation,Timeisthenameoftheclass,andprint_timeisthenameofthemethod.startis passedas aparameter.The second (and moreconcise) way istousemethod syntax:>>> start.print_time()09:45:00In this use of dot notation, print_time is the name of the method (again), and start is the objectthe method is invoked on, which is called the subject. Just as the subject of a sentence is what thesentence isabout, the subject of amethod invocation iswhat themethod isabout.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!