nested classes
Skip Montanaro
skip at pobox.com
Mon Jun 18 20:21:23 EDT 2001
Bjorn> But that's an implementation detail only, since it works
Bjorn> perfectly for functions:
Bjorn> def foo():
Bjorn> foo()
Only because at the point that foo calls itself recursively, the definition
of foo is in the module's global symbol table, assuming foo is def'd at the
module scope. If foo is nested inside another function, it can't call
itself directly without some help from the function it's enclosed in.
Before nested scopes, the following won't work:
% python
Python 2.1.1a1 (#10, Jun 8 2001, 14:37:03)
[GCC 2.96 20000731 (Linux-Mandrake 8.0 2.96-0.48mdk)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> if 1:
... def bar():
... def foo(i=0):
... if i < 10:
... foo(i+1)
... foo()
... bar()
...
<stdin>:2: SyntaxWarning: local name 'foo' in 'bar' shadows use of 'foo' as global in nested scope 'foo'
Traceback (most recent call last):
File "<stdin>", line 7, in ?
File "<stdin>", line 6, in bar
File "<stdin>", line 5, in foo
NameError: global name 'foo' is not defined
>>> from __future__ import nested_scopes
>>> if 1:
... def bar():
... def foo(i=0):
... if i < 10:
... foo(i+1)
... foo()
... bar()
...
>>>
When defining a class, the code within the class's scope is executed
immediately, before a class object has been bound to the class's name.
--
Skip Montanaro (skip at pobox.com)
(847)971-7098
More information about the Python-list
mailing list