dynamic class/module use? (like Java's forName)
Alex Hunsley
lard at tardis.ed.ac.molar.uk
Sun Jul 18 14:52:59 EDT 2004
Terry Reedy wrote:
> "Alex Hunsley" <lard at tardis.ed.ac.molar.uk> wrote in message
> news:8glKc.31979$v7.20488 at fe2.news.blueyonder.co.uk...
>
>> if (actionString == "blah"):
>> blahThang = blah(constructor stuff)
>> blahThang.doSomething()
>> else if (actionString == "blah2"):
>> blahThang2 = blah2(constructor stuff)
>> blahThang2.doSomething()
>> else if (actionString == "blah3"):
>> blahThang3 = blah3(constructor stuff)
>> blahThang3.doSomething()
>> else if (actionString == "blah2"):
>> # etc etc
>
>
> The Python idiom for something like the above is to use a dict instead of
> if/else.
> It is especially useful when you want to add alternatives at runtime.
> Something like
>
> actions = { 'blah':blah, 'blah2', blah2, 'blah3':blah3, ...}
> # easily extended at runtime
> ...
> actions[actionString](constructor_stuff).doSomething
>
> Terry J. Reedy
Interesting, I hadn't thought of using a dict.
Using a dict would be better than 'if's, but would still require a
central part of the code to know about all the actions!
My way allows new classes to be presented and used without altering
existing code.
Also my method forces new actions to interface with 'central' code via
the available official interface, rather than having new actions
potentially put in the central code and hence have access to things
directly (which isn't a good OO design).
More information about the Python-list
mailing list