Python Programming: An Introduction to Computer Science

(Nora) #1
11.4. COMBININGLISTSANDCLASSES 185

We wanttoreplacetheselineswithcodetocreatea listofpips.Oneapproachwouldbetostartwithan
emptylistofpipsandbuildupthefinallistonepipat a time.


pips = []
pips.append(self.makePip(cx-offset, cy-offset))
pips.append(self.
makePip(cx-offset, cy))
pips.append(self.makePip(cx-offset, cy+offset))
pips.append(self.
makePip(cx, cy))
pips.append(self.makePip(cx+offset, cy-offset))
pips.append(self.
makePip(cx+offset, cy))
pips.append(self.__makePip(cx+offset, cy+offset))
self.pips = pips


Anevenmorestraightforwardapproachis tocreatethelistdirectly, enclosingthecallsto makePip
insidelistconstructionbrackets,like this:


self.pips = [ self.makePip(cx-offset, cy-offset)),
self.
makePip(cx-offset, cy)),
self.makePip(cx-offset, cy+offset)),
self.
makePip(cx,cy)),
self.makePip(cx+offset, cy-offset)),
self.
makePip(cx+offset, cy)),
self.__makePip(cx+offset, cy+offset))
]


Noticehow I have formattedthisstatement.Ratherthanmakingonegiantline,I putonelistelementoneach
line. Pythonis smartenoughtoknowthattheendofthestatementhasnotbeenreacheduntilit findsthe
matchingsquarebracket.Listingcomplex objectsoneperlinelike thismakesit mucheasiertoseewhatis
happening.Justmake suretoincludethecommasat theendofintermediatelinestoseparatetheitemsofthe
list.
Theadvantageofa piplistis thatit is mucheasiertoperformactionsontheentireset.Forexample,we
canblankoutthediebysettingallofthepipstohave thesamecolorasthebackground.


for pip in self.pips:
pip.setFill(self.background)


Seehow thesetwo linesofcodeloopthroughtheentirecollectionofpipsto changetheircolor?Thisrequired
sevenlinesofcodeinthepreviousversionusingseparateinstancevariables.
Similarly, wecanturna setofpipsbackonbyindexingtheappropriatespotin thepipslist.Intheoriginal
program,pips1, 4, and7 wereturnedonforthevalue3.


self.pip1.setFill(self.foreground)
self.pip4.setFill(self.foreground)
self.pip7.setFill(self.foreground)


Inthenew version,thiscorrespondstopipsinpositions0, 3 and6, sincethepipslistis indexedstartingat 0.
A parallelapproachcouldaccomplishthistaskwiththesethreelinesofcode:


self.pips[0].setFill(self.foreground)
self.pips[3].setFill(self.foreground)
self.pips[6].setFill(self.foreground)


Doingit thiswaymakesexplicitthecorrespondencebetweentheindividualinstancevariablesusedin thefirst
versionandthelistelementsusedinthesecondversion.Bysubscriptingthelist,wecangetat theindividual
pipobjects,justasif they wereseparatevariables.However, thiscodedoesnotreallytake advantageofthe
new representation.
Hereis aneasierwaytoturnonthesamethreepips:

Free download pdf