[Tutor] Dynamic Function Assignment
John Fouhy
john at fouhy.net
Fri Oct 21 03:02:35 CEST 2005
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??
Perhaps a dictionary?
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)
If your MyObject instances are going to be constructed in a systematic
way, then you could simplify your definition of myObjects a bit more.
Eg:
objectData = [('A', 1), ('B', 2), ('C', 3)] # etc
myObjects = dict([(c, MyObject(id=id)) for c, id in objectData])
Hope this helps!
--
John.
More information about the Tutor
mailing list