Classes with initialization

Alex Martelli aleax at
Mon Apr 9 16:57:21 CEST 2007

<kyosohma at> wrote:
> > Also: can someone enlighten me as to when code in class scope is run,
> > exactly?

It's run as a part of the execution of the class statement.

> > if a class A has a metaclass M, then M.__init__ does not seem to get
> > the code in A's class scope in its arguments AFAICS, so I guess that
> > code is run before the class is created?

Right.  Nutshell 2nd ed, p 83 under "The class statement":

The nonempty sequence of statements that follows the class statement is
known as the class body.  A class body executes immediately as part of
the class statement's execution.  Until the body finishes executing, the
new class object does not yet exist and the classname identifier is not
yet bound (or rebound).  "How a Metaclass Creates a Class" on p. 118
provides more details about what happens when a class statement

The key to the latter part of the explanation (which actually starts on
p. 117:-) is that the class body executes in a temporary dictionary, say
d; that d is then used to help determine the meclass M (it may direct it
by having a key '__metaclass__'); then, d is passed as one of the three
arguments to the call to M (preceded by the classname string and the
tuple of the class's bases) -- lastly, the classname is bound or rebound
to the result of that call.

> As I understand it, class code doesn't get run until you create an
> instance of the class and call a method with that instance. I don't

No, this delay applies to code that's part of methods defined in the
class, but not to code that appears directly in classbody.  Easy to

>>> class Greet(object):
...   print 'hello world'
hello world

As you see, although no instance of the class has yet been created, the
print statement that's directly in classbody has already run.  If you
want to check that it runs _before_ the metaclass gets called, set a
custom metaclass that also does a print in its __init__, and see in what
order the print statements execute...


More information about the Python-list mailing list