Question about code writing '% i, callback'

Ian Kelly ian.g.kelly at gmail.com
Mon Nov 30 13:24:23 EST 2015


On Mon, Nov 30, 2015 at 10:36 AM, fl <rxjwg98 at gmail.com> wrote:
> Thanks for the replies. Now, I have the following code:
>
>
>
> class buibutton():
>     print 'sd'
>     def __nonzero__(self):
>        return False
>
>     def Button(self, ii, callbackk):
>         callbackk()
>         return
> UI=buibutton()
>
>
> for i in range(10):
>     def callback():
>         print "clicked button", i
>     UI.Button("button %s" % i, callback)
>
>
> To my surprise, the output is not the original link expected. i.e. it is
> the same with binding to the current values:

The callback function is being called immediately, in the body of the
loop, not stored and called later. The value of i in the closure has
not actually changed yet at the point you're calling it. If you
instead store the callback and call it later, you'll find that each
message says "button 9".



More information about the Python-list mailing list