> I've written code that looks a lot like that, and it's > a perfectly acceptable pattern IMHO. I don't bother > with the variables ON and OFF, though, as they add no > clarity to simply using 'ON' and 'OFF' for the states. > > [...] > The test portion of the code is actually longer than > the class > itself :-) > > That's usually a good thing! It means your code is > concise, and your tests are exhaustive. (But that > doesn't mean you can't also refactor your tests.)
I have a habit of falling into the ole' "re-invent the wheel" trap. As long as I can be thurough without veering too far off course i'm in good shape. --------------------------------------------------------------------------------------------------- > > 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!" Thanks for mentioning that as I have never looked at PEP-08 before (just looked it up) and I bookmarked it for future reference. > What about: > > class LightBulb(object): > def __init__(self, state): > self.state = state > > def switch(self): > self.state = not self.state > > (snip) I never thought about it using a switch. Steven eluded to it (toggle) in his re-write of the code. I plan on using that idea. > > I would like to be able to get a good hold of the concept > > state machines ? Well both state machines and classes (objects). That may be a bit of a tall order to take on all at once but the concepts seem to be quite related. I already have a great deal of material on Classes so good to go there. The state machine idea came from a game tutorial I was reading and it really sparked my interest. > > 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). > Thanks. Found some good FSM articles, that should help. -- http://mail.python.org/mailman/listinfo/python-list