"object" vs "dynamic" programming styles

Scottie me at nospam.net
Sun Mar 25 02:09:34 EST 2001


"Just van Rossum" <just at letterror.com> wrote in message
news:3ABD2390.A2A28A12 at letterror.com...
> "Edward C. Jones" wrote:
> > Here are three methods for doing the same thing. When is it better to
use
> > one of the approaches rather than another?
>
> > # Program 3
> >
> > # The function New_X returns an instance of either class A or class B.
> > def New_X(c):
> >     if c == 'a':
> >         return A()
> >     if c == 'b':
> >         return B()
>
> My personal preference would definitely be version 3, the factory
function.
> Less magic, clearer code.

I concur, but would cause an exception when your cases don't match.
This inspires a variation as follows:

    generators = {'a':A, 'b':B, 'c':C}

    def New_X(c):
         return generators[c]()

-Scott David Daniels







More information about the Python-list mailing list