Python Programming: An Introduction to Computer Science

(Nora) #1
5.3.USINGGRAPHICALOBJECTS 65

Figure5.3:Variousshapesfromthegraphicsmodule.

BecauseFidois aninstanceofthisclass,weexpectcertainthings.Fidohasfourlegs,a tail,a cold,wetnose
andhebarks.If Rex is a dog,weexpectthathewillhave similarproperties,eventhoughFidoandRex may
differinspecificdetailssuchassizeorcolor.
Thesameideasholdforourcomputationalobjects.We cancreatetwo separateinstancesofPoint, say
pandp2. Eachofthesepointshasanxandyvalue,andthey bothsupportthesamesetofoperationslike
getXanddraw. ThesepropertiesholdbecausetheobjectsarePoints.However, differentinstancescan
varyinspecificdetailssuchasthevaluesoftheircoordinates.
To createa new instanceofa class,weusea specialoperationcalledaconstructor. A callto a constructor
is anexpressionthatcreatesa brandnew object.Thegeneralformis asfollows.


(,, ...)

Hereis thenameoftheclassthatwewanttocreatea newinstanceof,e.g.,Circleor
Point. Theexpressionsintheparenthesesareany parametersthatarerequiredtoinitializetheobject.The
numberandtypeoftheparametersdependsontheclass. APointrequirestwo numericvalues,whilea
GraphWincanbeconstructedwithoutany parameters.Typically, a constructoris usedontherightsideof
anassignmentstatement,andtheresultingobjectis immediatelyassignedtoa variableontheleftsidethatis
thenusedtomanipulatetheobject.
To take a concreteexample,let’s lookatwhathappenswhenwecreatea graphicalpoint. Hereisa
constructorstatementfromtheinteractive exampleabove.


p = Point(50,60)


TheconstructorforthePointclassrequirestwo parametersgivingthexandycoordinatesforthenew point.
Thesevaluesarestoredasinstancevariables insideoftheobject.Inthiscase,Pythoncreatesaninstance
ofPointhavinganxvalueof 50 andayvalueof60.Theresultingpointis thenassignedtothevariable
p. Aconceptualdiagramoftheresultis showninFigure5.4.Notethat,inthisdiagramaswellassimilar
oneslateron,onlythemostsalientdetailsareshown.Points alsocontainotherinformationsuchastheir
colorandwhichwindow (ifany)they aredrawnin.Mostofthisinformationis settodefaultvalueswhenthe
Pointis created.
To performanoperationonanobject,wesendtheobjecta message.Thesetofmessagesthatanobject
respondstoarecalledthemethodsoftheobject.Youcanthinkofmethodsasfunctionsthatlive insideofthe
object.A methodis invokedusingdot-notation.


.(, , ...)

Thenumberandtypeoftheparametersis determinedbythemethodbeingused.Somemethodsrequireno
parametersat all.Youcanfindnumerousexamplesofmethodinvocationintheinteractive examplesabove.
Asexamplesofparameterlessmethods,considerthesetwo expressions.