2013-01-09 53 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

也感谢你。我现在明白了。 :) –

相关问题