metaclass that inherits a class of that metaclass?

Michael Spencer mahs at telcopartners.com
Wed Jun 1 17:25:17 EDT 2005


ironfroggy wrote:
> Hoping this isn't seeming too confusing, but I need to create a
> metaclass and a class using that metaclass, such that one of the bases
> of the metaclass is the class created with that metaclass. I can't
> figure out a way to do this, even after trying to add the class as a
> base after the classes have been created.
> 
> Is there some way I can get this to work properly?
> 
What do you have, and how doesn't it work?

I get:

  >>> class meta(type): pass
  ...
  >>> class cls(object):
  ...     __metaclass__ = meta
  ...     def __repr__(cls):
  ...         return "I'm %s, an instance of %s" % (cls.__name__, type(cls))
  ...
  >>> meta.__bases__ = (cls,)+meta.__bases__
  >>> cls
  I'm cls, an instance of <class 'meta'>
  >>> assert type(cls) in cls.__subclasses__()
  >>>

Of course, re-assigning meta.__bases__ comes too late to affect the construction 
sequence of cls.

Michael




More information about the Python-list mailing list