On 2/3/19 9:03 PM, Avi Gross wrote:

> The example I show above could in many cases be done as you describe
> but what are you gaining?
>
> I mean if I subtract the integer representation of a keyboard
> alphabetic letter (ASCII for the example) from letter 'a' or 'A' then
> A maps to 0 and B maps to 1 and ...  Z maps to 26. So, you could make
> a list of 26 functions (some may be absent) and your entire switch
> statement looks like:
>
>    funcs=[zeroeth,first,other,...,last] # list of function handles
>    var=input("Enter a Command: ")
>    if ord('A') <= ord(var[0]) <= ord('Z'):
>            result = funcs[ord(var[0]) - ord('A')]()
>
> Is that short enough?

It's not a matter of shortness.  Your code encapsulates the idea of
dispatching to a 0-airity function based on an input.  In Python,
though, I'd still use a dictionary, which would be more flexible (what
if I start to use digits or other characters as commands?)  and less
error prone.

> Your comment about object polymorphism is interesting. I am picturing
> how each choice somehow delivers an object that automatically is set
> up to do the right thing.

Disclaimer:  I speak OO as a second language, and only when there is an
obvious and compelling advantage over some other paradigm.  That said:

If the mapping from input to function is more complex than A -> func1, B
-> func2, etc., then a factory function that builds an object with an
execute method is a good way of isolating the mapping and keeping the
main code clean and clear.

> Again, see how can you write a COMPLICATED try command that captures
> many things including real errors?

Don't do that.  Why are you writing COMPLICATED try commands?

Did you have a Python question?  ;-)
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to