class factory

David M. Cook davecook at nowhere.net
Wed Aug 20 04:47:01 EDT 2003


In article <8ad2cfb3.0308200015.4f5bd504 at posting.google.com>, Nick Keighley
wrote:

> I'm a Python beginner and I'm would like to write a function that
> returns a class (perhaps a tad ambitious...). I've looked through
> the FAQ and perused "Python In  A Nutshell" (not a good book to
> start with?). The only example I found in PiaN used a simple
> if statement to return one of a selection of pre-existing classes.
> I'd like to generate a class on-the-fly from a parameter (a dictionary).
> Can Python do this sort of stuff? Does the mean I have to mess with
> the dreaded meta-classes?

You can create classes on the fly using "type"

>>> type('Foo', (object,), {})
<class '__main__.Foo'>

The arguments are the class name, a tuple of base classes, and a dictionary
of methods.

See http://python.org/2.2/descrintro.html#factories

Dave Cook




More information about the Python-list mailing list