[Tutor] designing POOP

Tiger12506 keridee at jayco.net
Sat Feb 9 00:20:00 CET 2008


> This is something that one can only gain from experience?
> I really had to struggle to get the Light class to work at all.
> I have no idea how many times I started over. But I do feel
> that I am starting to learn some of this stuff.

This surprises me... I guess it does take experience. What is the most basic 
thing you can describe about a light? Immediately I answer, "You can turn it 
on or off". This suggests methods, turn_on(), turn_off(), and something to 
maintain the state of the light attribute - i.e. whether it is currently on 
or not. I suggest practice practice practice. You should be able to look at 
anything in your house and be able to design a basic class for it. Some that 
come to mind as I look around the room. I've often thought of redesigning my 
entire house in OOP. ;-)

(Granted - these examples aren't entirely useful, but they provide examples 
of practice with methods and attributes.)

class Pen:
  def __init__(self):
    self.level = 50
    self.on = False
  def click(self):
    self.on = (not self.on)
  def isempty(self):
    return (self.level > 0)
  def write(self):
    if self.isempty:
      return False
    if not self.on:
      return False
    self.level = self.level - 5
    return True

class Knob:
  def __init__(self, locked=False):
    self.locked = locked
  def turn(self):
    if self.locked:
      return False
    return True

class Door:
  def __init__(self):
    self.knob = Knob()
  def lock(self):
    self.knob.locked = True
  def unlock(self):
    self.knob.locked = False
  def open(self):
    return self.knob.turn()

Are some simple examples off the top of my head. It's not difficult to model 
real-life things with classes, but it is much more difficult to model them 
in such a way that you interact with them normally. (i.e. do you lock the 
door, or the knob? Does the knob contain a Lock, or does the developer only 
need to know that it has one and whether it is locked or not?) 



More information about the Tutor mailing list