oct 25
- go over homework (Craps)
- discuss chapter 10 - classes (i.e. objects)
# Remember:
myCircle = Circle( Point(0,0), 20)
myCircle.draw(win)
myCircle.move(dx, dy)
...
- multi-sided die class
- This is the example in the text.
- Si: are we having fun yet?
# msdie.py
# Class definition for an n-sided die
from random import randint
class MSDie:
"Simulates a multi-sided dice."""
def __init__(self, sides):
self.sides = sides
self.value = 1
def roll(self):
self.value = randint(1,self.sides)
def getValue(self):
return self.value
def setValue(self, value)
self.value = value
- This can be put at the top of the program file ...
- or put in another file (a module).
- Then in the main program
# if class definition is in another file msdie.py
from msdie import MSDie
die1 = MSDie(6) # create a new 6-sided die
die1.roll() # roll it.
print "You rolled a", die1.value # access its value
- Caveat: must exit interactive python and re-load classes; old defs can hang around.
- having methods getFoo and setFoo is very common: called "accessors"
- the constructor is always (in Python) named __init__
- the "self" word is special: it always refers to the thing itself, in its methods
- and it must be listed first in method definitions
- ... but not in method calls
# essentially these two calls are the same :
roll(die1)
die1.roll()
# inside the roll() method,
#'self' will be the 'die1' object during either of these last two.