Python Programming: An Introduction to Computer Science

(Nora) #1
164 CHAPTER10. DEFININGCLASSES

a = input("Enterthe launch angle (in degrees): ")
v = input("Enterthe initial velocity (in meters/sec): ")
h = input("Enterthe initial height (in meters): ")
t = input("Enterthe time interval between position calculations:")
return a,v,h,t

def main():
angle, vel, h0, time= getInputs()
cball = Projectile(angle,vel, h0)
while cball.getY()>= 0:
cball.update(time)
print "\nDistancetraveled: %0.1f meters." % (cball.getX())


10.4 ObjectsandEncapsulation


10.4.1 EncapsulatingUsefulAbstractions.


Hopefully, youcanseehowdefiningnewclassescanbea goodwaytomodularizea program. Oncewe
identifysomeobjectsthatmightbeusefulinsolvinga particularproblem,wecanwriteanalgorithmasif we
hadthoseobjectsavailableandpushtheimplementationdetailsintoa suitableclassdefinition.Thisgivesus
thesamekindofseparationofconcernsthatwehadusingfunctionsintop-downdesign.Themainprogram
onlyhastoworryaboutwhatobjectscando,notabouthow they areimplemented.
Computerscientistscallthisseparationofconcernsencapsulation. Theimplementationdetailsofan
objectareencapsulatedintheclassdefintion,whichinsulatestherestoftheprogramfromhavingtodeal
withthem. Thisisanotherapplicationofabstraction(ignoringirrelevantdetails),whichis theessenceof
gooddesign.
I shouldmentionthatencapsulationis onlya programmingconventionin Python.It is notenforcedbythe
language,perse.InourProjectileclassweincludedtwo shortmethods,getXandgetY, thatsimply
returnedthevaluesofinstancevariablesxposandypos, respectively. Strictlyspeaking,thesemethodsare
notabsolutelynecessary. InPython,youcanaccesstheinstancevariablesofany objectwiththeregulardot
notation.Forexample,wecouldtesttheconstructorfortheProjectileclassinteractivelybycreatingan
objectandthendirectlyinspectingthevaluesoftheinstancevariables.





c = Projectile(60,50, 20)
c.xpos
0.0
c.ypos
20
c.xvel
25.0
c.yvel
43.301270





Accessingtheinstancevariablesofanobjectlike thisis veryhandyfortestingpurposes,but it is generally
consideredpoorpracticeto thisin programs.Oneofthemainreasonsforusingobjectsis to insulateprograms
thatusethoseobjectsfromtheinternaldetailsofhow they areimplemented.Referencesto instancevariables
shouldremaininsidetheclassdefinitionwiththerestoftheimplementationdetails.Fromoutsidetheclass,
ourinteractionwithanobjectshouldtake placeusingtheinterfaceprovidedbyitsmethods.Asyoudesign
classesofyourown,youshouldstrive toprovidea completesetofmethodstomake yourclassuseful.That
wayotherprogramsdonotneedtoknow aboutormanipulateinternaldetailslike instancevariables.


10.4.2 PuttingClassesinModules.


Oftena well-definedclassorsetofclassesprovide(s)usefulabstractionsthatcanbeleveragedinmany
differentprograms.We mightwanttoturnourprojectileclassintoitsownmodulefilesothatit canbeused

Free download pdf