Create a new class on the fly
Alex Martelli
aleax at mac.com
Thu May 31 00:22:39 EDT 2007
py_genetic <conor.robinson at gmail.com> wrote:
> Is this possible or is there a better way. I need to create a new
> class during runtime to be used inside a function. The class
> definition and body are dependant on unknows vars at time of exec,
> thus my reasoning here.
>
> class PosRecords(tables.IsDescription):
>
>
> class A(object):
> self.__init__(self, args):
This makes 0 sense; maybe you should learn elementary Python syntax well
_before_ trying advanced stuff, no?
> ........
> def mkClass(self, args):
> eval( "class B(object): ...") #definition on B is dependant
> on dynamic values in string
> ......do stuff with class
Just use a class statement, and setattr on the resulting class object to
set stuff dynamically on it. eval won't do what you want (it takes
expressions, not statements), and exec is an even worse way to go about
it.
E.g.:
class A(object):
def mkClass(self, name, *k):
class bah(object): pass
bah.__name__ = name
for n in k: setattr(bah, n, k[n])
return bah
Alex
More information about the Python-list
mailing list