difference between class statement and def statement (WAS Re: End of file)
Steven Bethard
steven.bethard at gmail.com
Mon Oct 11 01:58:03 EDT 2004
Andrew Durdin <adurdin <at> gmail.com> writes:
> Another [sort-of related] question: why does the following not produce
> a NameError for "foo"?
>
> def foo(): print foo
> foo()
I'm thinking this was meant to be "left as an exercise to the reader" ;), but
just in case it wasn't, you've exactly illustrated the difference between a
class definition statement and a function definition statement. Executing a
class definition statement executes the class block, while executing a
function definition statement only initializes the function object, without
actually executing the code in the function's block. Hence:
>>> class C(object):
... print C
...
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in C
NameError: name 'C' is not defined
The name of a class is bound to the class object at the end of the execution
of a class statment. Since executing a class statement executes the code in
the class's block, this example references C before it has been bound to the
class object, hence the NameError.
>>> def f():
... print f
...
>>> f()
<function f at 0x009D6670>
The name of a function is bound to the function object when the def statement
is executed. However, the function's code block is not executed until f is
called, at which point the name f has already been bound to the function
object and is thus available from the globals.
Steve
More information about the Python-list
mailing list