Class Factories in Python: How?

Alex cut_me_out at hotmail.com
Mon May 1 14:57:55 EDT 2000


> # A Nicer way? Is it possible?
> # class factory to specialize the above class given some new attributes
> # to use:
> def marshalstruct_factory(newattributes):
>     class newclass(marshalstruct):
> 	  attributes = newattributes
> 	  lookups = binstruct_lookup(attributes)
> 	  fieldcount = len(attributes)
>     return newclass
> 
> # fails, attributes = newattributes doesn't work, probably because the
> # above class scope doesn't admit the function parameters into its
> # scope.

If this is the main problem, there may be a way around it.  Could you do
something like this:

def marshalstruct_factory(newattributes):
    class newclass(marshalstruct):
	pass
    newclass.attributes = newattributes
    newclass.lookups = binstruct_lookup(attributes)
    newclass.fieldcount = len(attributes)
    return newclass

Alex.



More information about the Python-list mailing list