Python Programming: An Introduction to Computer Science

(Nora) #1

Chapter 10


Defining Classes


Inthelastthreechapters,wehave developedtechniquesforstructuringthecomputationsofa program.In
thenextfew chapters,wewilltake a lookat techniquesforstructuringthedatathatourprogramsuse.You
alreadyknow thatobjectsareoneimportanttoolformanagingcomplex data.Sofar, ourprogramshave made
useofobjectscreatedfrompre-definedclassessuchasCircle. Inthischapter, youwilllearnhow towrite
yourownclassessothatyoucancreatenovel objects.


10.1 QuickReview ofObjects


RememberbackinChapter5,I definedanobjectasanactive datatypethatknowsstuff andcandostuff.
Moreprecisely, anobjectconsistsof



  1. A collectionofrelatedinformation.

  2. A setofoperationstomanipulatethatinformation.


Theinformationis storedinsidetheobjectininstancevariables. Theoperations,calledmethods, arefunc-
tionsthat“live”insidetheobject.Collectively, theinstancevariablesandmethodsarecalledtheattributesof
anobject.
To take a now familiarexample,aCircleobjectwillhave instancevariablessuchascenter, which
remembersthecenterpointofthecircle,andradius, whichstoresthelengthofthecircle’s radius.The
methodsofthecirclewillneedthisdatatoperformactions.Thedrawmethodexaminesthecenterand
radiustodecidewhichpixelsina window shouldbecolored.Themovemethodwillchangethevalueof
centertoreflectthenew positionofthecircle.
Recallthateveryobjectis saidtobeaninstanceofsomeclass. Theclassoftheobjectdetermineswhat
attributestheobjectwillhave.Basicallya classis a descriptionofwhatitsinstanceswillknow anddo.New
objectsarecreatedfroma classbyinvokingaconstructor. Youcanthinkoftheclassitselfasa sortoffactory
forstampingoutnew instances.
Considermakinga new circleobject:


myCircle = Circle(Point(0,0),20)


Circle, thenameoftheclass,is usedtoinvoke theconstructor. Thisstatementcreatesa newCircle
instanceandstoresa referencetoit inthevariablemyCircle. Theparameterstotheconstructorareused
toinitializesomeoftheinstancevariables(namelycenterandradius) insideofmyCircle. Oncethe
instancehasbeencreated,it is manipulatedbycallingonitsmethods:


myCircle.draw(win)
myCircle.move(dx, dy)
...


155
Free download pdf