Python Programming: An Introduction to Computer Science

(Nora) #1
12.5. EXERCISES 223

We couldhave usedinheritancetobuildourpokerprogram.WhenwefirstwrotetheDieViewclass,
it didnotprovidea wayofchangingtheappearanceofthedie.We solvedthisproblembymodifyingthe
originalclassdefinition.Analternative wouldhave beentoleave theoriginalclassunchangedandcreate
a newsubclassColorDieView. AColorDieViewis justlike aDieViewexceptthatit containsan
additionalmethodthatallowsustochangeitscolor. Hereis how it wouldlookinPython:


class ColorDieView(DieView):


def setValue(self,value):
self.value= value
DieView.setValue(self,value)

def setColor(self,color):
self.foreground= color
self.setValue(self.value)

Thefirstlineofthisdefinitionsaysthatwearedefininga newclassColorDieViewthatisbased
on(i.e.,a subclassof)DieView. Insidethenewclass,wedefinetwo methods. Thesecondmethod,
setColor, addsthenew operation.Ofcourse,inordertomakesetColorwork,wealsoneedtomodify
thesetValueoperationslightly.
ThesetValuemethodinColorDieViewredefinesoroverridesthedefinitionofsetValuethatwas
providedin theDieViewclass.ThesetValuemethodin thenew classfirststoresthevalueandthenrelies
onthesetValuemethodofthesuperclassDieViewtoactuallydraw thepips.Noticeespeciallyhow the
callto themethodfromthesuperclassis made.Thenormalapproachself.setValue(value)wouldre-
ferto thesetValuemethodoftheColorDieViewclass,sinceselfis aninstanceofColorDieView.
InordertocalltheoriginalsetValuemethodfromthesuperclass,it is necessarytoputtheclassname
wheretheobjectwouldnormallygo.


DieView.setValue(self,value)


Theactualobjecttowhichthemethodis appliedis thensentasthefirstparameter.


12.5 Exercises



  1. Inyourownwords,describetheprocessofOOD.

  2. Inyourownwords,defineencapsulation,polymorphismandinheritance.

  3. AddbellsandwhistlestothePokerDicegame.

  4. Redoany ofthedesignproblemsfromChapter9 usingOOtechniques.

  5. Findtherulestoaninterestingdicegameandwriteaninteractive programtoplayit.Someexamples
    areCraps,Yacht,GreedandSkunk.

  6. Writea programthatdealsfourbridgehands,countshowmany pointsthey have andgivesopening
    bids.

  7. Finda simplecardgamethatyoulike andimplementaninteractive programtoplaythatgame.Some
    possibilitiesareWar, Blackjack,varioussolitairegames,andCrazyEights.

  8. Writeaninteractive programfora boardgame.SomeexamplesareOthello(Reversi),ConnectFour,
    Battleship,Sorry!,andParcheesi.

Free download pdf