Python Programming: An Introduction to Computer Science

(Nora) #1
10.4. OBJECTSANDENCAPSULATION 165

inotherprograms.Indoingso,it wouldbea goodideatoadddocumentationthatdescribeshowtheclass
canbeusedsothatprogrammerswhowanttousethemoduledon’t have tostudythecodetofigureout(or
remember)whattheclassanditsmethodsdo.
Youarealreadyfamiliarwithonewayofdocumentingprograms,namelycomments.It’s alwaysa good
ideatoprovidecommentsexplainingthecontentsofa moduleanditsuses.Infact,commentsofthissort
aresoimportantthatPythonincorporatesa specialkindofcommentingconventioncalledadocstring. You
caninserta plainstringliteralasthefirstlineofa module,classorfunctiontodocumentthatcomponent.
Theadvantageofdocstringsis that,whileordinarycommentsaresimplyignoredbyPython,docstringsare
actuallycarriedalongduringexecutionina specialattributecalled doc. Thesestringscanbeexamined
dynamically.
MostofthePythonlibrarymoduleshave extensive docstringsthatyoucanusetogethelponusingthe
moduleoritscontents.Forexample,if youcan’t rememberhow tousetherandrangefunction,youcan
printitsdocstringlike this:





import random
print random.randrange.doc
Choose a random itemfrom range(start, stop[, step]).





Hereis a versionofourProjectileclassasa modulefilewithdocstringsincluded:

projectile.py


"""projectile.py
Provides a simple classfor modeling the flight of projectiles."""


from math import pi, sin,cos


class Projectile:


"""Simulates the flightof simple projectiles near the earth’s
surface, ignoringwind resistance. Tracking is done in two
dimensions, height(y) and distance (x)."""

def __init__(self,angle, velocity, height):
"""Create a projectilewith given launch angle, initial
velocity and height."""
self.xpos = 0.0
self.ypos = height
theta = pi * angle/ 180.0
self.xvel = velocity* cos(theta)
self.yvel = velocity* sin(theta)

def update(self,time):
"""Update the stateof this projectile to move it timeseconds
farther intoits flight"""
self.xpos = self.xpos+ time * self.xvel
yvel1 = self.yvel- 9.8 * time
self.ypos = self.ypos+ time * (self.yvel + yvel1) / 2.0
self.yvel = yvel1

def getY(self):
"Returns the y position(height) of this projectile."
return self.ypos

def getX(self):
Free download pdf