New user's initial thoughts / criticisms of Python
Thomas Rachel
nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Sun Nov 10 07:24:31 EST 2013
Am 09.11.2013 14:27 schrieb Joshua Landau:
> `select` is quite an odd statement, in that in most cases it's just a
> weaker variant of `if`. By the time you're at the point where a
> `select` is actually more readable you're also at the point where a
> different control flow is probably a better idea. Things like
> dictionaries or a variables pointing to functions are really useful
> and can be encapsulated in a class quite well. This is a bit more
> advanced but largely more rigorous.
class Switch(object):
def __init__(self, value):
self.value = value
self.called = False
def case(self, other):
def wr(func):
if not self.called and self.value == other:
self.called = True
return func(self.value)
return wr
def default(self, func):
if not self.called:
self.called = True
return func(self.value)
if __name__ == '__main__':
import random
while 1:
n = random.randrange(0, 5)
sw = Switch (n)
@sw.case(1)
def _(n): print n, "is one"
@sw.case(2)
def _(n): print n, "is two"
@sw.default
def _(n): print n, "is something else"
More information about the Python-list
mailing list