substitute for c/java's ?:

Neil Macneale mac4-devnull at theory.org
Thu Jun 14 02:35:54 EDT 2001


In article <9g5fc4$m8u$01$1 at news.t-online.com>, "Jochen Riekhof"
<jochen at riekhof.de> wrote:

> I am missing something like the c/Java ?: operator.

The ?: operator is overrated. For the time you save typing, you
are wasting someone else's because they need to figure out what you were
thinking.


> if elif else is not a proper substitute for switches, as the variable in

I have found that using a dictionary of function pointers sometimes gives
the switch statement feel.  For example, point to constructors...

cases = {"dog": Dog, "cat": Cat, "rabbit": Rabbit}

def createPet(type="cat"):
    if casses.has_key(type): return casses[type]() #Good input...
    else: return None   # bad input, or 'default' in C/java

The above code is generally hard to read, so use sparingly and comment 
well.  The thing I like about it is that the keys can be of any type. One
problem is that all the functions called are going to need similar
parameters,  but sometimes its a usefull trick.

> Otherwise, one of the coolest languages I learned so far!!
> 
I agree! I have found very few people make an effort at python and then
end up saying it sucks.  I can't say the same for my effort with perl.

Neil Macneale

--
To reply to me via email, remove the '-devnull' from my address.



More information about the Python-list mailing list