Question about code writing '% i, callback'

fl rxjwg98 at gmail.com
Mon Nov 30 12:36:09 EST 2015


On Monday, November 30, 2015 at 11:44:44 AM UTC-5, fl wrote:
> Hi,
> 
> I come across the following code snippet.
> 
> 
> 
> 
> 
> for i in range(10):
>     def callback():
>         print "clicked button", i
>     UI.Button("button %s" % i, callback)
> 
> 
> 
> 
> The content inside parenthesis in last line is strange to me. 
> 
> "button %s" % i, callback
> 
> 
> That is, the writing looks like recognized as three items when I try with a
> class definition (it can run with this):
> 
> class buibutton():
>     print 'sd'
>     def __nonzero__(self):
>        return False
>        
>     def Button(str, ii, callbackk):
>         
>         return
> 
> 
> Could you explain it to me?
> 
> The link is here:
> 
> http://effbot.org/zone/default-values.htm
> 
> Thanks,

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:

for i in range(10):
    def callback(i=i):


I have the output for both:


%run "C:/Users/CCS6_1_Tiva_C/Python_prj0/uibutton1.py"
sd
clicked button 0
clicked button 1
clicked button 2
clicked button 3
clicked button 4
clicked button 5
clicked button 6
clicked button 7
clicked button 8
clicked button 9

%run "C:\Users\CCS6_1_Tiva_C\Python_prj0\uibutton0.py"
sd
clicked button 0
clicked button 1
clicked button 2
clicked button 3
clicked button 4
clicked button 5
clicked button 6
clicked button 7
clicked button 8
clicked button 9

I don't know why it does not have the not expected format output:

sd
clicked button 9
clicked button 9
clicked button 9
clicked button 9
clicked button 9
clicked button 9
clicked button 9
clicked button 9
clicked button 9
clicked button 9


Thanks,



More information about the Python-list mailing list