162 CHAPTER10. DEFININGCLASSES
OK,soselfis a parameterthatrepresentsanobject.Butwhatexactlycanwedowithit?Themain
thingtorememberis thatobjectscontaintheirowndata.Instancevariablesprovidestoragelocationsinside
ofanobject.Justaswithregularvariables,instancevariablesareaccessedbyname.We canuseourfamiliar
dotnotation: object . instance-var . LookatthedefinitionofsetValue;self.valuerefersto
theinstancevariablevaluethatis storedinsidetheobject.Eachinstanceofa classhasitsowninstance
variables,soeachMSDieobjecthasitsveryownvalue.
Certainmethodsina classhave specialmeaningtoPython.Thesemethodshave namesthatbeginand
endwithtwo underscores.Thespecialmethod init is theobjectconstructor. Pythoncallsthismethod
toinitializea newMSDie. Theroleof init is toprovideinitialvaluesfortheinstancevariablesofan
object.
Fromoutsidetheclass,theconstructoris referredtobytheclassname.
die1 = MSDie(6)
Whenexecutingthisstatement,Pythoncreatesa newMSDieandexecutes init onthatobject.Thenet
resultis thatdie1.sidesis setto6 anddie1.valueis setto1.
Thepowerofinstancevariablesis thatwecanusethemtorememberthestateofa particularobject,and
thisinformationthengetspassedaroundtheprogramaspartoftheobject.Thevaluesofinstancevariables
canbereferredtoagaininothermethodsoreveninsuccessive callstothesamemethod.Thisis different
fromregularlocalfunctionvariableswhosevaluesdisappearoncethefunctionterminates.
Hereis a simpleillustration:
die1 = Die(13)
print die1.getValue()
1
die1.setValue(8)
print die1.getValue()
8
Thecalltotheconstructorsetstheinstancevariabledie1.valueto1.Thenextlineprintsoutthisvalue.
Thevaluesetbytheconstructorpersistsaspartoftheobject,eventhoughtheconstructoris overanddone
with. Similarly, executingdie1.setValue(8)changestheobjectbysettingitsvalueto8. Whenthe
objectis askedforitsvaluethenexttime,it respondswith8.
That’s justaboutallthereis toknow aboutdefiningnew classesinPython.Now it’s timetoputthisnew
knowledgetouse.
10.3.2 Example:TheProjectileClass.
Returningtothecannonballexample,wewanta classthatcanrepresentprojectiles.Thisclasswillneeda
contructorto initializeinstancevariables,anupdatemethodtochangethestateoftheprojectile,andgetX
andgetYmethodssothatwecanfindthecurrentposition.
Let’s startwiththeconstructor. Inthemainprogram,wewillcreatea cannonballfromtheinitialangle,
velocityandheight.
cball = Projectile(angle,vel, h0)
TheProjectileclassmusthave an init methodthatusesthesevaluestoinitializetheinstance
variablesofcball. Butwhatshouldtheinstancevariablesbe?Ofcourse,they willbethefourpiecesof
informationthatcharacterizetheflightofthecannonball:xpos,ypos,xvelandyvel. We willcalculate
thesevaluesusingthesameformulasthatwereintheoriginalprogram.
Hereis how ourclasslookswiththeconstructor:
class Projectile:
def __init__(self,angle, velocity, height):
self.xpos = 0.0
self.ypos = height