Case Statements
Christian Gollwitzer
auriocus at gmx.de
Wed Mar 16 04:13:48 EDT 2016
Am 16.03.16 um 05:26 schrieb Mark Lawrence:
> So you would rather write something like:-
>
> switch (x):
> case COW:
> moo()
> break
>
> case DUCK:
> quack()
> break
>
> default IDUNNO:
> panic()
>
> than:-
>
> x.makeNoise()
No sane person would do that. But just because you selected the worst
possible semantics (fallthrough/break) and the worst posible use case
(simulating polymorphism) doesn't mean that switches have no use. Code
like the above was used a lot in early GUI toolkits for C - Motif and
the Windows C API, for instance, use a gigantic switch to decide upon
incoming events. Now the strange statement in the switch discussion
makes sense:
"Typically, similar switch statements are scattered throughout a
program. If you add or remove a clause in one switch, you often have to
find and repair the others too."
That happens indeed if one were to simulate polymorphism using switch
statements, but not for other cases.
In Python, you need to go the other way round, you don't have a switch,
but you can simulate it via function tables or polymorphism.
The difference between a switch and its simulation via function pointer
tables etc. is the scope. In a true switch statement, the code blocks
access the same variables. You can't truly simulate an if statement in
Python, if it were missing:
>>> def hi():
... print "hi"
...
>>> def yu():
... print "yu"
...
>>> hi() if 1>2 else yu()
yu
>>> hi() if 2>1 else yu()
hi
This gives you, in principal, an if-then-else statement back. But you
can't do something like
if 1>2:
a=3
else:
b=2
Same with switch. You can use a hash table etc. to simulate switches,
but only if the codeblocks are independent. Otherwise, if-elif chains
are the way to go. Command line parsing is a case where switch
statements are often used, e.g. in shell scripts.
Christian
More information about the Python-list
mailing list