Any simpler way to do this
Bruno Desthuilliers
bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Dec 7 04:17:56 EST 2007
Lars Johansen a écrit :
> I have a function that looks like this:
>
> def Chooser(color):
<mode="pedant">
Bad naming (noun instead of a verb) and not conformant to PEP 08
(function names should be all_lower)
</mode>
> if color == "RED":
> x = term.RED
> elif color == "BLUE":
> x = term.BLUE
> elif color == "GREEN":
> x = term.GREEN
> elif color == "YELLOW":
> x = term.YELLOW
> elif color == "CYAN":
> x = term.CYAN
> elif color == "MAGENTA":
> x = term.MAGENTA
> return x
What do you think will happen if I call it like this:
Chooser(42)
(if you answered 'will raise a NameError', then you're correct).
>
> Wouldn there been easier if I could just skip all the "*if's" and just
> "return term.color", however this gives a syntax error, are there any
> clever way to do this ?
getattr(obj, name) is your friend.
More information about the Python-list
mailing list