class declaration shortcut

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Wed Feb 28 15:57:27 EST 2007


Luis M. González a écrit :
> I've come across a code snippet in www.rubyclr.com where they show how
> easy it is to declare a class compared to equivalent code in c#.
> I wonder if there is any way to emulate this in Python.
> 
> The code is as follows:
> 
> Person = struct.new( :name, :birthday, :children)

s/struct/Struct/

> I tried something like this, but it's nothing close to what I'd like:
> 
> def klass(table, *args):
> 	cls = new.classobj(table, (), {})
> 	for i in args:
> 		setattr(cls, i, i)
> 	return cls
> 
> But this above is not what I want.
> I guess I should find a way to include the constructor code inside
> this function, but I don't know if this is possible.
> Also, I wonder if there is a way to use the variable name in order to
> create a class with the same name (as in "Person"above).
> 
> Well, if anyone has an idea, I'd like to know...

Here's a *very* Q&D attempt - that doesn't solve the name problem:
def Struct(name, *attribs):
     args = ", ".join("%s=None" % attr for attr in attribs)
     body = "\n            ".join("self.%s = %s" % (attr, attr) \
                                   for attr in attribs)
     source = ("""
     class %s(object):
         def __init__(self, %s):
             %s
     """.strip()) % (name, args, body)
     #print source
     code = compile(source, 'dummy', 'single')
     exec code
     return locals()[name]

But note that I'd immediatly fire anyone using such an abomination in 
production code.




More information about the Python-list mailing list