John Fouhy wrote:
> On 21/10/05, Greg Lindstrom <[EMAIL PROTECTED]> wrote:
> 
>> Suppose I have three objects...
>>
>> a = MyObject(id=1)
>> b = MyObject(id=2)
>> c = MyObject(id=3)
>>
>> segment = 'A Segment to Process'
>>
>> for id in ('A', 'B', 'C'):
>>    if segment.upper().startswith(id):
>>       ??how can I select the correct object here with a big "if"
>>statement??
> 
> Something like:
> 
> myObjects = { 'A':MyObject(id=1), 'B':MyObject(id=2), 'C':MyObject(id=3) }
> for c in ('A', 'B', 'C'):
>   if segment.upper().startswith(c):
>     myObjects[c].doSomething(segment)

This can be simplified even further to something like
key = segment[0].upper()
myObjects[key].doSomething(segment)

This will raise an exception if segment doesn't start with A, B or C. But the 
idea is that once you have a dictionary you can look up segment directly.

To handle the exception you can use a try/except block or use a default handler.

Kent

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to