problem in using metaclasses to inspect Python code

Michele Simionato mis6 at pitt.edu
Fri Dec 13 14:36:41 EST 2002


Greg Chapman <glc at well.com> wrote in message news:<f0vjvuc27srm79dldiveu3devbghp37phi at 4ax.com>...
> Ignoring metaclasses for the moment, suppose we had:
> 
> class C(object):
>     pass
> 
> class D(C):
>     pass
> 
> c = C()
> 
> Now suppose you want to change the __class__ of c from C to D.  You can do this
> in Python:
> 
> c.__class__ = D
> 
> but you certainly wouldn't expect c's __init__ method to be called again (at
> least I hope you ouldn't).
> 
> The case is just the same for metaclasses:

It is so obvious now ! (but it was not obvious at all before!)

> you could do away with the class
> statement entirely if you wanted.  E.g.:
> 
> >>> D = type('D', (object,), {})
> >>> def sayHi(cls):
> ...     print 'hi from Meta'
> ...     print 'class instance is', cls.__name__
> ...
> >>> Meta = type('Meta', (type,), {'sayHi': sayHi})
> >>> D.__class__ = Meta
> >>> D.sayHi()
> hi from Meta
> class instance is D
> >>> E = Meta('E', (), {})
> >>> E.sayHi()
> hi from Meta
> class instance is E
> >>> e = E()
> >>> e.__class__
>  <class '__main__.E'>
> >>> e.__class__.__class__
> <class '__main__.Meta'>
> 
> ---

Yes, I have understood the use of "type" now (unfortunately not documented in
the standard docs, you have to study very carefully Guido's essay on
"Unifying types and classes" to find an extremely concise reference to 
its second syntax :-(), see my last posting.

> Greg Chapman

Thanks again,

    Michele



More information about the Python-list mailing list