166 CHAPTER10. DEFININGCLASSES
"Returns the x position(distance) of this projectile."
return self.xpos
Youmightnoticethatmany ofthedocstringsinthiscodeareenclosedintriplequotes(”””). Thisis a
thirdwaythatPythonallowsstringliteralsto bedelimited.Triplequotingallowsusto directlytypemulti-line
strings. Hereis anexampleofhow thedocstringsappearwhenthey areprinted.
print projectile.Projectile.doc
Simulates the flightof simple projectiles near the earth’s
surface, ignoringwind resistance. Tracking is done in two
dimensions, height(y) and distance (x).
Ourmainprogramcouldnow simplyimportthismoduleinordertosolve theoriginalproblem.
cball4.py
from projectile importProjectile
def getInputs():
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())
Inthisversion,detailsofprojectilemotionarenow hiddenintheprojectilemodulefile.
10.5 WidgetObjects
Oneverycommonuseofobjectsis inthedesignofgraphicaluserinterfaces(GUIs).BackinChapter5,we
talkedaboutGUIsbeingcomposedofvisualinterfaceobjectscalledwidgets. TheEntryobjectdefinedin
ourgraphicslibraryis oneexampleofa widget.Nowthatweknowhowtodefinenewclasses,wecan
createourowncustomwidgets.
10.5.1 ExampleProgram:DiceRoller.
Let’s tryourhandatbuildinga coupleusefulwidgets.Asanexampleapplication,considera programthat
rollsa pairofstandard(six-sided)dice. Theprogramwilldisplaythedicegraphicallyandprovidetwo
buttons,oneforrollingthediceandoneforquittingtheprogram.Figure10.3showsa snapshotoftheuser
interface.
Youcanseethatthisprogramhastwo kindsofwidgets:buttonsanddice.We canstartbydeveloping
suitableclasses.Thetwo buttonswillbeinstancesofaButtonclass,andtheclassthatprovidesa graphical
view ofthevalueofa diewillbeDieView.
10.5.2 BuildingButtons
Buttons,ofcourse,arestandardelementsofvirtuallyeveryGUIthesedays.Modernbuttonsareveryso-
phisticated,usuallyhavinga 3-dimensionallookandfeel.Oursimplegraphicspackagedoesnothave the
machinerytoproducebuttonsthatappeartodepressasthey areclicked.Thebestwecandois findoutwhere