[EMAIL PROTECTED] wrote: > Bruno Desthuilliers wrote: > >>[EMAIL PROTECTED] wrote: >> >>>Hi >>> >>>I'd like to use metaclasses to dynamically generate a class based on a >>>parameter to the objects init function. >> >>Do you really need a metaclass for this ? >> >> >>>For example: >>> >>>class MetaThing(type): >>> def __init__(cls, name, bases, dict, extra_information): >>> super(MetaThing, cls).__init__(name, bases, dict) >>> #setup the class based on the parameter extra_information >>> >>>class Thing: >>> __metaclass__ = MetaThing >>> def __init__(self, extra_information): >>> #Somehow pass extra_information to the MetaThing >>> >>>extra_information = 1 >>>t = Thing(extra_information) >> >>Why would you want a new *class* here ? >> >> >>>The above sample won't work but I hope it demonstrates what I'm trying >>>to do. >> >>Not enough, I'm afraid - unless it's just me being dumb. From what I see >>here, you just can add the extra informations on the object in the >>initializer. What's your *real* use case ? >> > > The extra_information is used in MetaThing to tell it what attributes > to add to the class. For example: > > class MetaThing(type): > def __init__(cls, name, bases, dict, extra_information): > super(MetaThing, cls).__init__(name, bases, dict) > #setup the class based on the parameter extra_information > setattr(cls, make_name(extra_information), > make_object(extra_information)) > > Does that clarify things? I might have the wrong approach
There's at least something wrong here : the metaclass code is executed when the class statement (the one for a class having this metaclass) is eval'd. It won't be called on class instanciation. http://www.python.org/download/releases/2.2.3/descrintro/#__new__ Also, you need to understand that modifying a class with impact all it's instances. > - I'm new to > metaclasses. However I do think the solution to my problem lies with > them since I have to dynamically generate a class You don't have to create classes for this - it's perfectly legal to set attributes (data or methods) on a per-object basis. Classes are more object-factories than rigid types. Just add the needed extra attributes in the __init__ (the class one, not the metaclass) and you should be done. > and metaclasses > provide a mechanism for doing this. Metaclasses provides a hook on class creation process. But AFAICT, you don't necessarily need metaclasses to dynamically create classes... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list