A
Alexander May
When I define a function in the body of a loop, why doesn't the function
"close" on the loop vairable? See example below.
Thanks,
Alex
C:\Documents and Settings\Alexander May>python
Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
.... return x
.... l.append(f)
....[<function f at 0x008E66F0>, <function f at 0x008E6AB0>, <function f at
0x008EC130>, <function f at 0x008EC170>, <functi
on f at 0x008EC1B0>, <function f at 0x008EC1F0>, <function f at 0x008EC230>,
.... f()
....
9
9
9
9
9
9
9
9
9
9
On the other hand, the following works as I expected.
.... return x
.... return f
........ l.append(makef(x))
....[<function f at 0x008E6AB0>, <function f at 0x008EC330>, <function f at
0x008EC1F0>, <function f at 0x008EC230>, <functi
on f at 0x008EC270>, <function f at 0x008EC2B0>, <function f at 0x008EC0F0>,
.... f()
....
0
1
2
3
4
5
6
7
8
9
"close" on the loop vairable? See example below.
Thanks,
Alex
C:\Documents and Settings\Alexander May>python
Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
.... def f():l=[]
for x in xrange(10):
.... return x
.... l.append(f)
....[<function f at 0x008E66F0>, <function f at 0x008E6AB0>, <function f at
0x008EC130>, <function f at 0x008EC170>, <functi
on f at 0x008EC1B0>, <function f at 0x008EC1F0>, <function f at 0x008EC230>,
.... f()
....
9
9
9
9
9
9
9
9
9
9
On the other hand, the following works as I expected.
.... def f():l=[]
def makef(x):
.... return x
.... return f
........ l.append(makef(x))
....[<function f at 0x008E6AB0>, <function f at 0x008EC330>, <function f at
0x008EC1F0>, <function f at 0x008EC230>, <functi
on f at 0x008EC270>, <function f at 0x008EC2B0>, <function f at 0x008EC0F0>,
.... f()
....
0
1
2
3
4
5
6
7
8
9