Help With Better Design

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Wed Jun 20 08:13:11 EDT 2007


apollonius2 at gmail.com a écrit :
> Greetings,
> 
> I have been working on a little project today to help me better
> understand classes in Python (I really like Python). I am a self
> taught programmer and consider myself to fall in the "beginner"
> category for sure. It was initially sparked by reading about "state
> machines". This was my attempt at it however I feel it is not quite
> where it should be:
> 

First, a few general comments

> ON  = "ON"
> OFF = "OFF"
 >
> class LightBulb:

Better to use newstyle classes:
  class LightBulb(object):

>     def __init__(self, initial_state):
>         self.state = initial_state
> 
>     def TurnOn(self):

Pep-08 (naming conventions):
       def turn_on(self):

>         if self.state == OFF:
>             self.state = ON
>         else:
>             print "The Bulb Is Already ON!"
> 
>     def TurnOff(self):
>         if self.state == ON:
>             self.state = OFF
>         else:
>             print "The Bulb Is Aleady OFF!"


What about:

class LightBulb(object):
   def __init__(self, state):
     self.state = state

   def switch(self):
     self.state = not self.state

(snip)

> I would like to be able to get a good hold of the concept

state machines ?

> with this example before I try to model a more complex problem. Would
> someone be willing to give me some feedback on this class and whether
> I am on the right track or how I might better go about it?

There is a lot to say about OO and state machines. Someone once defined 
the use of OO in simulations as "building an big unpredictable state 
machine from small predictable state machines". As a matter of fact, 
objects are (most of the time) informal state machines (they have state, 
and they have behaviour depending on state). Now there are much more 
formal state machines (google for "FSM" or "finite state machine") - 
which can be implemented in a lot of ways - including the "State" design 
pattern.

Before jumping to implementation, you should probably try to model the 
"more complex problem" with something like UML state diagram (one of the 
few usable things in UML).

My 2 cents



More information about the Python-list mailing list