[Tutor] instantiating subclass by parameter

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Oct 29 12:08:24 EST 2003



> > So why not bypass the factory and just do:
> >
> > classes = {'AltaVista':AltaVista,'WebSearch':WebSearch,...}
> >
> > a = classes['AltaVista']()
> > b = classes['WebSearch']()
>
> Yup, I've done that too.  I've done both solutions, the factory and
> a dict style one, like above.

Hi Karl,

By the way, we can see a concrete example of this 'plugin' style system in
the Standard Library.


The 'codecs' library works by keeping a module-level dictionary of all the
encodings that it knowns about, and whenever we do something like:

    'foobar'.encode('utf-8')

it envokes the codecs system, which looks up an instance of a UTF-8
encoder from that internal dictionary.  Their system is a bit more
sophisticated, but its essence is similar to what you're doing.

    http://www.python.org/doc/lib/module-codecs.html


Another example of a plugin-style system is in xml.sax() --- its
make_parser() function is a "factory" that returns XMLReader objects.

    http://www.python.org/doc/lib/module-xml.sax.html



> As I learn python some of my perl habits keep coming back. The
> there-is-more-than-one-way-to-do-it philosophy is deeply ingrained.

Not necessarily a bad thing.  *grin*


Good luck to you!




More information about the Tutor mailing list