|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Stop making mediocre tutorials.The best tutorials are video! Camtasia Studio makes it easy to create engaging, buzz-building screen videos at any size, in any popular format. Download the free trial!
|
|
#1
|
|||
|
|||
|
"if" Alternative
I'm parsing an inputed string for commands, and I was wondering if there is a better way to associate the inputed commands with their action than just using ifs
i.e. Code:
if command == 'foo':
doStuff()
if command == 'bar':
foo = 0
doMoreStuff()
...
|
|
#2
|
|||
|
|||
|
Yes there is - use a dispatch table. e.g.
Code:
dispatchTable = {
'foo' : doStuff,
'bar' : doMoreStuff,
#etc
}
dispatchTable[command]()
This does have some limitations - each of your actions must be packed into separate functions. In your original code the 'bar' command sets foo=0 before the call to doMoreStuff, which would not be possible using this technique. Sadly Python does not have anonymous code blocks, which would make this technique more powerful. You could possibly simulate it using eval and the compiler module, but it would probably be more trouble than it is worth. Regards, Dave - The Developers' Coach |
|
#3
|
|||
|
|||
|
Dave's way is the python way alternative to the switch statement.
If you're looking for switch, it was intentionally left out of python for the same reasons as removing +=,-=,etc .. as well as leaving out a host of other things such as condition?ret_true:ret_false. Python maintains the highest clarity (as far as code readability goes) as well as removing possible causes of bugs. Alot of ppl forget about the break in switch statements which causes alot of bugs. Also if/elif/else is the clearest code for the job as far as readability goes.. |
|
#4
|
|||
|
|||
|
It's it just me or do '+=' and '-=' work? I'm guessing you mean the increment and decrement operators (++ and --).
|
|
#5
|
|||
|
|||
|
ah crap .. yeh that's wot I meant =P
|
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > "if" Alternative |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|