Slight metaclass confusion

Stephan Diehl stephan.diehl at
Tue Sep 9 13:54:00 CEST 2003

ben at wrote:

> I am slightly confused about the way metaclasses work, having read
> "Metaclass Programming In Python, Parts 1 and 2"
> I get the fact that the instance of a metaclass is a class, but in
> this case I fail to see why the following does'nt work:
>>>> class Meta(type):
> ...     def __str__(cls):
> ...             print "I am " + repr(cls)
> ...
>>>> Class = Meta("Fish", (), {})
>>>> Class.__str__()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: descriptor '__str__' of 'object' object needs an argument
> Whereas this does:
>>>> class Simple(object):
> ...     def __str__(self):
> ...             return "I am " + repr(self)
> ...
>>>> obj = Simple()
>>>> obj.__str__()
> I am <__main__.Simple object at 0x402f676c>
> The tutorial does mention this (slightly), but doesn't make it clear
> why this is happening. I am probably missing something obvious though!

The problem is perhaps the terminology (Unfortunatelly,I don't know a better

The metaclass initializes a class. Just imagine, that the textual class
definition comes fresh from the parser, so you have information about
possible base classes, methods, attributes. These information can be
changed within the metaclass __new__ method.
Think of the metaclass as a factory that turns a class definition into a
class instance.
Other than that, they don't interact.

What a metaclass can do, is to change that information, before the class is
made into a class object.

Basicly, the metaclass concept is orthogonal to the inheritence concept of

> Thanks for the help,
> Ben
> ---

Hope that helps


More information about the Python-list mailing list