2013-01-09 54 views
3

我知道這是一個noob問題,但我試圖弄清楚爲什麼「self.update_count」,在從'create_widget'方法調用它時不需要括號。我一直在尋找,但無法找出原因。Python - 爲什麼在另一個實例方法中調用這個實例方法時不需要括號?

請幫忙。

# Click Counter 
# Demonstrates binding an event with an event handler 

from Tkinter import * 

class Skeleton(Frame): 
    """ GUI application which counts button clicks. """ 
    def __init__(self, master): 
     """ Initialize the frame. """ 
     Frame.__init__(self, master) 
     self.grid() 
     self.bttn_clicks = 0 # the number of button clicks 
     self.create_widget() 

    def create_widget(self): 
     """ Create button which displays number of clicks. """ 
     self.bttn = Button(self) 
     self.bttn["text"] = "Total Clicks: 0" 
     # the command option invokes the method update_count() on click 
     self.bttn["command"] = self.update_count 
     self.bttn.grid() 

    def update_count(self): 
     """ Increase click count and display new total. """ 
     self.bttn_clicks += 1 
     self.bttn["text"] = "Total Clicks: "+ str(self.bttn_clicks) 

# main root = Tk() root.title("Click Counter") root.geometry("200x50") 

app = Skeleton(root) 

root.mainloop() 

回答

2
self.update_count() 

是將方法的調用,所以

self.bttn["command"] = self.update_count() 

將結果從該方法存儲在self.bttn。然而,

self.bttn["command"] = self.update_count 

沒有括號店方法本身self.bttn。在Python,方法和函數是對象,你可以繞過,存放於變量等

作爲一個簡單的例子,考慮下面的程序:

def print_decimal(n): 
    print(n) 

def print_hex(n): 
    print(hex(n)) 

# in Python 2.x, use raw_input 
hex_output_wanted = input("do you want hex output? ") 

if hex_output_wanted.lower() in ('y', 'yes'): 
    printint = print_hex 
else: 
    printint = print_decimal 

# the variable printint now holds a function that can be used to print an integer 
printint(42) 
+0

噢,好的。謝啦。 –

0

它不是從那個叫方法。它使用對函數的引用,該按鈕稍後會在單擊時調用。你可以把它看作一個函數的名字,作爲對該函數中代碼的引用;調用你應用()運算符的函數。

+0

感謝您解決這個問題。非常感激。 –

1

這不是一個函數調用,但字典內的基準記憶:

self.bttn["command"] = self.update_count 
// stores reference to update_count inside self.bttn["command"] 
// invokable by self.bttn["command"]() 

最有可能Button對象具有呼籲某些相互作用這種方法的能力。

+0

也感謝你。我現在明白了。 :) –

相關問題