160 CHAPTER10. DEFININGCLASSES
10.3.1 Example:Multi-SidedDice
Youknow thata normaldie(thesingularofdice)is a cubeandeachfaceshowsa numberfromonetosix.
Somegamesemploy nonstandarddicethatmayhave fewer(e.g.,four)ormore(e.g.,thirteen)sides. Let’s
designa generalclassMSDietomodelmulti-sideddice.^1 We couldusesuchanobjectinany numberof
simulationorgameprograms.
EachMSDieobjectwillknow two things.
- How many sidesit has.
- Itscurrentvalue.
Whena newMSDieiscreated,wespecifyhowmany sidesit willhave,n. We canthenoperateonthe
diethroughthreeprovidedmethods:roll, tosetthedietoa randomvaluebetween1 andn, inclusive;
setValue, tosetthedietoa specificvalue(i.e.,cheat);andgetValue, toseewhatthecurrentvalueis.
Hereis aninteractive exampleshowingwhatourclasswilldo:
die1 = MSDie(6)
die1.getValue()
1
die1.roll()
die1.getValue()
4
die2 = MSDie(13)
die2.getValue()
1
die2.roll()
die2.getValue()
12
die2.setValue(8)
die2.getValue()
8
Doyouseehowthismightbeuseful?I candefineany numberofdicehavingarbitrarynumbersofsides.
Eachdiecanberolledindependentlyandwillalwaysproducea randomvaluein theproperrangedetermined
bythenumberofsides.
Usingourobject-orientedterminology, wecreatea diebyinvokingtheMSDieconstructorandproviding
thenumberofsidesasa parameter. Ourdieobjectwillkeeptrackofthisnumberinternallyusinganinstance
variable.Anotherinstancevariablewillbeusedtostorethecurrentvalueofthedie.Initially, thevalueof
thediewillbesettobe1,sincethatis a legalvalueforany die.Thevaluecanbechangedbytherolland
setRollmethodsandreturnedfromthegetValuemethod.
Writinga definitionfortheMSDieclassis reallyquitesimple.Aclassis a collectionofmethods,and
methodsarejustfunctions.Hereis theclassdefinitionforMSDie:
msdie.py
Class definitionfor an n-sided die.
from random importrandrange
class MSDie:
def __init__(self,sides):
self.sides= sides
self.value= 1
(^1) Obviously, thenameMSDieis shortfor“Multi-SidedDie”andis notintendedasa commentonany softwaregiant,realorfictional,
whichmayormaynotemploy unfairmonopolostictradepracticestothedetrimentofconsumers.