class constructors: class vs. instance defaults

Lenard Lindstrom len-1 at telus.net
Thu Oct 7 15:14:02 EDT 2004


Carlos Ribeiro <carribeiro at gmail.com> writes:

> On Wed, 6 Oct 2004 16:39:50 -0600, Erik Johnson <ej
> <at at bag.python.org>wellkeeper <"dot>com"@bag.python.org> wrote:
> > ...
> > <snip>
> > ...
> >     You might be surprised to find out that all the Bar objects end up
> > sharing the same foo_d dictionary.
> 
> Yes, they will share. And you explanation is correct. The default
> arguments are evaluated only once, when the def() is executed.
> 
> Now an explanation on what I mean when I say 'the def() is executed'.
> It took me a while to really 'get' it, and I would not be surprised if
> anyone ever made the same mistake.
> 
> -- When Python reads you code, it compiles it to bytecode. That's the
> first step. It will always do it before execution.
> 
> -- It then executes your code -- *the entire code*. It includes class
> definitions and function definitions.
> 
> -- In the case of class definitions, it really executes the class
> statement body, but only once. After executing the class statement
> body, it creates a class with all the symbols defined there. It's much
> more flexible than a simple compilation step. When you instantiante a
> object, it just reads this definition and calls the proper constructor
> (__init__).
> 
> -- In the case of the def() -- or function definition -- it really
> 'executes the def() statement', which is not the same thing as to say
> that it will execute its body. Understand? The def statement has an
> effect -- it creates a function object, and associates it with the
> code of the function. The default arguments are evaluated at this time
> and also stored as part of the function object (you can do all types
> of nice stuff with function objects, if that's something you like...
> but I'll leave that for other opportunity).
> 
> -- Of course, the function body is executed only when you call it, by
> referring to the function object.
> 
> That's it, in a nutshell.
>  
This is essentially correct but leaves an opening for misunderstanding.
The assertion "-- It then executes your code -- *the entire code*." is
ambiguous. Only code reached during normal program flow is executed.
The python class and def statements are no exception. They are executed
each and every time they are encountered in the currently executing block
of code. If a definition is in a part of the code that is never reached
then that class or function will never be created.

Definitions as executable statements have their advantages. Closures
rely on an enclosed function's def being executed each time the enclosing
function is called. And a module can use an if statement to control which
version of a class or function is created when the module is loaded.

Lenard Lindstrom
<len-l at telus.net>



More information about the Python-list mailing list