metaclasses (was Re: Hooks, aspect-oriented programming, and design by contract)

James_Althoff at i2.com James_Althoff at i2.com
Fri Jan 25 17:39:48 EST 2002


[Aahz Maruch]
>Just to make sure I'm getting this straight, in the past
>James Althoff has talked about Smalltalk's design, and IIRC,
>he said that in Smalltalk it is *instances* of metaclasses that
>create classes.  Can anyone confirm or deny?

Well, what I thought I had said (or meant to say, anyway <wink>) was that,
in Smalltalk, classes *are* instances of metaclasses.  Seen another way,
metaclasses are simply classes whose instances happen to be, themselves,
classes also.  Regular classes -- those that are *not* metaclasses -- are
not metaclasses solely by virtue of the fact that their instances are
objects that are *not* classes.

In Python, you can consider type Type to be a "metatype" in the same way.
"Instances" of type Type are themselves types.  Instances of types other
than type Type are objects that are *not* types.  So only type Type is a
"metatype" (talking pre-2.2, here).  (Type Type is an "instance" of itself.
In Smalltalk-76 -- before fullblown metaclasses were added in Smalltalk-80
-- class Class was an instance of itself, similarly.)

Python 2.2's metaclasses are like Smalltalk's in this regard.

Perhaps the confusion comes from this difference.  In Smalltalk there are
shortcuts such that if you create a class (using standard mechanisms) the
system will first create a corresponding metaclass for you.  Your newly
created class is an instance of said newly created metaclass.  The newly
created metaclass is the place where you add class methods for your newly
created class.  In Smalltalk class methods are no different than instance
methods.  You simply invoke a method on a class object and that process is
identical to invoking a method on any other kind of object.  For example
my_turtle.display() is a message to an instance (my_turtle) whereas
Turtle.new() is a message to a class object (Turtle) (using Python syntax,
here).  Note: it so happens that in the standard Smalltalk library every
class has a corresponding, separate metaclass.  But this is a design choice
and not a requirement of the language (IOW, Smalltalk allows multiple
classes to be instances of a given metaclass).

In Smalltalk metaclasses are useful because that is where you find class
methods.  In Python you can have "class methods" directly in class objects
(by marking them as class methods) so the need to create a metaclass to
change the behavior of a class is less common in Python than it is in
Smalltalk.

Jim





More information about the Python-list mailing list