2014-10-10 83 views
0

首先,我在Python中的初學者,所以準備了nooby問題))'Lambda格式'之間的區別究竟是什麼?

在本網站上的話題之一,我發現關於使用拉姆達的建議非常有用的一塊功能。

這裏是我的代碼更正前:

def entree1(self):     #function that is supposed to change text in 
self.configure(text = "X")    the label block from whatever it is to 'X' 

fen = Tk() 

pole1 = Label(fen, text = '|_|') 
pole1.bind("<Button-1>", lambda: entree1(pole1))   #event handler reffering to the function above 

這裏是我的代碼更正後:

def entree1(self):     #function that is supposed to change text in 
self.configure(text = "X")    the label block from whatever it is to 'X' 

fen = Tk() 

pole1 = Label(fen, text = '|_|') 
pole1.bind("<Button-1>", lambda x: entree1(pole1))   #event handler reffering to the function above 

概括地說,我改變拉姆達:一些FUNC拉姆達X:一些FUNC

它的工作,這是偉大的,但我無法弄清楚這兩個變種之間的區別。 您能否告訴我在添加x後究竟發生了什麼變化?

謝謝你的時間!

回答

1

讓我lambda表達式轉換到你可能更習慣於函數的定義:

lambda : entree1(pole1) 

相同

def lambdaFunc(): 
    global pole1 
    return entree1(pole1) 

你修正功能

lambda x : entree1(pole1) 

這與

相同
def lambdaFunc(x): 
    global pole1 
    return entree1(pole1) 

你需要額外的參數,因爲Tk按鈕調用它們綁定到一個變量的函數(我忘記了變量是什麼),因此調用帶有輸入變量的函數,當它不需要一個原因錯誤。

+2

'pole1'的'global'聲明是多餘的。 – jacg 2014-10-10 17:15:59

+0

啊,好吧,我想我明白了。對我而言,這仍然是一個相當古怪的概念,但我認爲真正的理解將隨着時間的推移而來。非常感謝你! – 2014-10-12 12:36:38