class factory

Helmut Jarausch jarausch at skynet.be
Wed Aug 20 04:46:50 EDT 2003


I'm quite new to Python, as well.

Nick Keighley wrote:
> Hi,
> 
> 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
   ^^^^^^^^^^^
Python in a Nutshell is an excellent book except if Python is your
very first programming language.
> 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?
> 

Have a look at ch 13 (top of page 262).
Build a string 'ClassDefinition',
call compile like
GenClassCode= compile(ClassDefinition,'my_class_def','exec')
and than in some context
exec(GenClassCode)
If 'ClassDefinition' generates a class 'X' just use it
like
newX= X(....)



-- 
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany





More information about the Python-list mailing list