[Tutor] Dynamic Function Assignment
Kent Johnson
kent37 at tds.net
Fri Oct 21 04:08:28 CEST 2005
John Fouhy wrote:
> On 21/10/05, Greg Lindstrom <tubaranger at gmail.com> 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
More information about the Tutor
mailing list