Ben C escribió:
> On 2006-04-21, Ben C <[EMAIL PROTECTED]> wrote:
> Having said that, I attempted to confirm this using def rather than
> lambda, and encountered something I cannot explain at all-- it appears
> that the functions are getting redefined whenever they are called, to
> effect a kind of "dynamic scoping" behaviour. I would appreciate any
> explanation anyone can give of this:
> 
> fns = []
> for y in range(2):
>       def fn():
>               yy = y      # exactly the same with yy = int(y)
>               print "defining fn that returns", yy
>               return yy
>       print "Appending at", y
>       print fn, fn()
>       fns.append(fn)


yy = y does assign y's current value (current == fn call time, not fn 
definition time). To return 0 and 1 as expected you should create a 
"different/private" y for every fn's definition.

----------------------------------------

fns = []
for y in range(2):
        def fn(y=y):
                yy = y
                print "defining fn that returns", yy
                return yy
        print "Appending at", y
        print fn, fn()
        fns.append(fn)


----------------------------------------

fns = []
def factory(y) :
        def fn() :
                yy = y
                print "defining fn that returns", yy
                return yy
        return fn

for y in range(2) :
        fn = factory(y)
        print "Appending at", y
        print fn, fn()
        fns.append(fn)

----------------------------------------


HTH
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to