Python Programming: An Introduction to Computer Science

(Nora) #1

Chapter 5


Objects and Graphics


Sofarwehave beenwritingprogramsthatusethebuilt-inPythondatatypesfornumbersandstrings.We
sawthateachdatatypecouldrepresenta certainsetofvalues,andeachhada setofassociatedoperations.
Basically, weviewedthedataaspassive entitiesthatweremanipulatedandcombinedviaactive operations.
Thisis a traditionalwaytoview computation.To buildcomplex systems,however, it helpstotake a richer
view oftherelationshipbetweendataandoperations.


Mostmoderncomputerprogramsarebuiltusinganobject-oriented(OO)approach.Objectorientation
is noteasilydefined.It encompassesa numberofprinciplesfordesigningandimplementingsoftware,prin-
ciplesthatwewillreturntonumeroustimesthroughoutcourseofthisbook.Thischapterprovidesa basic
introductiontoobjectconceptsbywayofsomecomputergraphics.


5.1 TheObjectofObjects.


Thebasicideaofobject-orienteddevelopmentistoviewa complex systemastheinteractionofsimpler
objects. Thewordobjectsisbeingusedhereina specifictechnicalsense. PartofthechallengeofOO
programmingis figuringoutthevocabulary. YoucanthinkofanOOobjectasa sortofactive datatypethat
combinesbothdataandoperations.To putit simply, objectsknowstuff(they containdata),andtheycando
stuff(they have operations).Objectsinteractbysendingeachothermessages.A messageis simplya request
foranobjecttoperformoneofitsoperations.


Considera simpleexample. Supposewewanttodevelopa dataprocessingsystemfora collegeor
university. We willneedtokeeptrackofconsiderableinformation. Forstarters,wemustkeeprecords
onthestudentswhoattendtheschool.Eachstudentcouldberepresentedintheprogramasanobject. A
studentobjectwouldcontaincertaindatasuchasname,IDnumber, coursestaken,campusaddress,home
address,GPA,etc. Eachstudentobjectwouldalsobeabletorespondtocertainrequests. Forexample,
tosendouta mailing,wewouldneedtoprintanaddressforeachstudent.Thistaskmightbehandledbya
printCampusAddressoperation.Whena particularstudentobjectis senttheprintCampusAddress
message,it printsoutitsownaddress. To printoutalltheaddresses,a programwouldloopthroughthe
collectionofstudentobjectsandsendeachoneinturntheprintCampusAddressmessage.


Objectsmayrefertootherobjects.Inourexample,eachcourseinthecollegemightalsoberepresented
byanobject. Courseobjectswouldknowthingssuchaswhotheinstructoris,whatstudentsareinthe
course,whattheprerequisitesare,andwhenandwherethecoursemeets.Oneexampleoperationmightbe
addStudent, whichcausesa studenttobeenrolledinthecourse. Thestudentbeingenrolledwouldbe
representedbytheappropriatestudentobject.Instructorswouldbeanotherkindofobject,aswellasrooms,
andeventimes.Youcanseehowsuccessive refinementoftheseideascouldleadtoa rathersophisticated
modeloftheinformationstructureofthecollege.


Asa beginningprogrammer, you’reprobablynotyetreadytotacklea collegeinformationsystem.For
now, we’ll studyobjectsinthecontextofsomesimplegraphicsprogramming.


61
Free download pdf