[Tutor] constants, flags or whatever
bob gailer
bgailer at alum.rpi.edu
Thu Dec 20 03:41:13 CET 2007
Jim Morcombe wrote:
> In a program, I want to set some kind of variable or object to
> indicate what "mode" the program is currently in.
> What is the most elegant way of doing this?
>
> Jim
> ---------------------------------------------------------------------------
> constant: moving = "m"
> constant: inserting = "i"
> constant:jumping = "j"
> .
> .
> action = moving
> .
> .
> .
> if action == jumping:
> jumpSomewhere()
> elseif action == moving:
> moveSomewhere()
> elseif action == inserting:
> insertSomething()
> ------------------------------------------------------------------------
1 - I see no value in introducing variables. I'd just use string constants:
action = "moving"
.
.
if action == "jumping":
etc.
2 - It is common in Python to use a dictionary to map the constants to
the functions instead of if-elif statements:
actions = dict( jumping = jumpSomewhere,
moving = moveSomewhere,
inserting = insertSomething)
the entire if-elif construct now becomes:
actions[action]()
adding new action-function pairs is now a lot easier.
More information about the Tutor
mailing list