10.3. DEFININGNEWCLASSES 161
def roll(self):
self.value= randrange(1,self.sides+1)
def getValue(self):
return self.value
def setValue(self,value):
self.value= value
Asyoucansee,a classdefinitionhasa simpleform:
class
Eachmethoddefinitionlookslike a normalfunctiondefinition.Placingthefunctioninsidea classmakesit a
methodofthatclass,ratherthana stand-alonefunction.
Let’s take a lookatthethreemethodsdefinedinthisclass. You’ll noticethateachmethodhasa first
parameternamedself. Thefirstparameterofa methodis special—italwayscontainsa referencetothe
objectonwhichthemethodis acting.Asusual,youcanuseany nameyouwantforthisparameter, butthe
traditionalnameisself, sothatis whatI willalwaysuse.
Anexamplemightbehelpfulinmakingsenseofself. Supposewehave amainfunctionthatexecutes
die1.setValue(8). Amethodinvocationis a functioncall.Justasinnormalfunctioncalls,Python
executesa four-stepsequence:
- Thecallingprogram(main) suspendsatthepointofthemethodapplication. Pythonlocatesthe
approriatemethoddefintioninsidetheclassoftheobjecttowhichthemethodis beingapplied.Inthis
case,controlis transferringtothesetValuemethodintheMSDieclass,sincedie1is aninstance
ofMSDie. - Theformalparametersofthemethodgetassignedthevaluessuppliedbytheactualparametersofthe
call.Inthecaseofa methodcall,thefirstformalparametercorrespondstotheobject.Inourexample,
it is asif thefollowingassignmentsaredonebeforeexecutingthemethodbody:
self = die1
value = 8
- Thebodyofthemethodis executed.
- Controlreturnstothepointjustafterwherethemethodwascalled,inthiscase,thestatementimmedi-
atelyfollowingdie1.setValue(8).
Figure10.2illustratesthemethod-callingsequenceforthisexample.Noticehow themethodis calledwith
oneparameter(thevalue),butthemethoddefinitionhastwo parameters,duetoself. Generallyspeaking,
wewouldsaysetValuerequiresoneparameter. Theselfparameterinthedefinitionis a bookkeeping
detail.Somelanguagesdothisimplicitly;Pythonrequiresustoaddtheextraparameter. To avoidconfusion,
I willalwaysrefertothefirstformalparameterofa methodastheselfparameterandany othersasnormal
parameters.So,I wouldsaysetValueusesonenormalparameter.
class MSDie:
...
def setValue(self,value):
self.value = value
def main():
die1 = MSDie(12)
die1.setValue(8)
print die1.getValue()
self=die1; value=8
Figure10.2:Flow ofcontrolincall:die1.setValue(8).