Using metaclassed to dynamically generate a class based on a parameter to the objects init function.

Maric Michaud maric at aristote.info
Fri Jun 23 17:09:08 CEST 2006


Le Vendredi 23 Juin 2006 16:03, Carl Banks a écrit :
> Don't follow?  The actual source code won't be much easier.  Here's an
> example.
>
>     class MetaThing(type):
>         def __new__(metacls,name,bases,clsdict,extra_information):
>             # use extra_information
>             return type.__new__(metacls,name,bases,clsdict)
>
>     class Thing(object):
>          def __new__(cls,extra_information):
>              clsdict = {'__new__':object.__new__}
>              my_very_own_class = MetaThing(
>                  "Subthing",(Thing,),clsdict,extra_information)
>              return object.__new__(my_very_own_class)

Hmmm, rigourously speaking, metaclasses in OOP are classes whose instances are 
class.
Something like that :

In [114]: class MetaClass(object) :
   .....:     def __new__(cls, name, bases=(), **some_attributes) :
   .....:         return type('newtype %s' % name, bases, some_attributes)
   .....:
   .....:


Let's play with it :


In [115]: Concrete1 = MetaClass('conc1', (), classprop=1, method=lambda 
s : "fun")

In [116]: Concrete2 = MetaClass('conc1', (), classprop=1, method=lambda 
s : "fun")

In [117]: isinstance(Concrete1(), Concrete2)
Out[117]: False

In [118]: isinstance(Concrete1(), Concrete1)
Out[118]: True

In [119]: Concrete1().method()
Out[119]: 'fun'

In [120]: Concrete1.classprop
Out[120]: 1

In [121]: class Abstract(object) :
   .....:     def __init__(self) : self._attr = self._attr_type()
   .....:
   .....:

In [122]: Concrete = MetaClass('concrete_with_list', (Abstract,), 
_attr_type=list)

In [123]: Concrete()._attr
Out[123]: []

In [124]: Concrete = MetaClass('concrete_with_int', (Abstract,), 
_attr_type=int)

In [125]: Concrete()._attr
Out[125]: 0

In [126]: type(Concrete)
Out[126]: <type 'type'>

In [127]: type(Concrete())
Out[127]: <class '__main__.newtype concrete_with_int'>


regards,



-- 
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097



More information about the Python-list mailing list