188 CHAPTER11. DATA COLLECTIONS
# Turn the appropriatepips back on
for i in self.onTable[value]:
self.pips[i].setFill(self.foreground)
11.5 CaseStudy:PythonCalculator
ThereworkedDieViewclassshowshow listscanbeusedeffectivelyasinstancevariablesofobjects.Inter-
estingly, ourpipslistandonTablelistcontaincirclesandlists,respectively, whicharethemselvesobjects.
Maintaininglistsofobjectscanbea powerfultechniquefororganizinga program.
We cangoonestepfurtherandviewa programitselfasa collectionofdatastructures(collectionsand
objects)anda setofalgorithmsthatoperateonthosedatastructures.Now, if a programcontainsdataand
operations,thenonenaturalwaytoorganizetheprogramit totreattheentireapplicationitselfasanobject.
11.5.1 A CalculatorasanObject
Asanexample,we’ll developa programthatimplementsa simplePythoncalculator. Ourcalculatorwill
have buttonsforthetendigits(0–9),a decimalpoint“.”, fouroperations(“+”,“-”,“*”,“/”),anda few special
keys:“C”toclearthedisplay, “ -” tobackspaceover charactersinthedisplay, and“=”todothecalculation.
We’ll take a verysimpleapproachtoperformingcalculations.Asbuttonsareclicked,thecorresponding
characterswillshowupinthedisplay, allowingtheusertocreatea formula.Whenthe“=”key is pressed,
theformulawillbeevaluatedandtheresultingvalueshowninthedisplay. Figure11.1showsa snapshotof
thecalculatorinaction.
Figure11.1:Pythoncalculatorinaction.
Basically, wecandividethefunctioningofthecalculatorintotwo parts:creatingtheinterfaceandinter-
actingwiththeuser. Theuserinterfaceinthiscaseconsistsofa displaywidgetanda bunchofbuttons.We
cankeeptrackoftheseGUIwidgetswithinstancevariables.Theuserinteractioncanbemanagedbya setof
methodsthatmanipulatethewidgets.
To implementthisdivisionoflabor, wewillcreateaCalculatorclassthatrepresentsthecalculator
inourprogram. Theconstructorfortheclasswillcreatetheinitialinterface.We willmake thecalculator
respondtouserinteractionbyinvokinga specialrunmethod.
11.5.2 ConstructingtheInterface
Let’s take a detailedlookat theconstructorfortheCalculatorclass.First,we’ll needtocreatea graphics
window todraw theinterface.