dynamic class instantiation
Kent Johnson
kent at kentsjohnson.com
Thu Feb 2 13:20:26 EST 2006
Ognen Duzlevski wrote:
> Volker Grabsch <volker_grabsch at v.notjusthosting.com> wrote:
>>I'm sure you could replace 2/3 of your code with something much simpler
>>(and shorter!) just by not inventing a new language and using the power
>>of Python instead.
>
>
> Hi Volker,
>
> I appreciate your comments. Basically, the reason why this code generator
> exists is the fact that I do not want to hard-code the resulting xml in
> any way. The users of the web/db framework of which this solution is part of
> might like the "web page" definition I offer them, but, some might want to extend it.
> While dom allows me to traverse an xml hierarchy - it does not allow me to
> give "meaning" to the tags. The only way to do that (for me) is to represent
> the tags as classes with containers containing other classes (tags) and so on. Since
> I do not know ahead of time what the tags will be - I need to generate the code
> to actually handle them.
>
> Can you suggest a better approach or did you already do that and I just missed
> it? :)
Instead of generating Python code and importing it, you could create the
classes directly. You would still have your own language but no code
generator.
For a very simple example, you could have a base class that initializes
attributes from a class dictionary:
class DynamicInits(object):
def __init__(self):
self.__dict__.update(self.inits)
and a simple factory function that creates a subclass with an
appropriate dict of initializers:
def classFactory(name, initializers):
return type(name, (DynamicInits,), {'inits' : initializers})
In your original post you show this class:
class page(object):
def __init__():
self.name = None
self.caption = None
self.functions = []
With the above definitions, an equivalent class is created by calling
page = classFactory( 'page', { 'name' : None, 'caption': None,
'functions' : []} )
Kent
More information about the Python-list
mailing list