Python - 为什么在另一个实例方法中调用此实例方法时不需要括号?

标签 python python-2.7

我知道这是一个菜鸟问题,但我想弄清楚为什么“self.update_count”在从“create_widget”方法调用时不需要括号。我一直在寻找,但找不到原因。

请帮忙。

# 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()

最佳答案

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)

关于Python - 为什么在另一个实例方法中调用此实例方法时不需要括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14232237/

相关文章:

python - 使用错误 : Line magic function `%sql` not found

python - Scrapy、privoxy 和 Tor : SocketError: [Errno 61] Connection refused

python - 如何用 Python 中的空格替换文本中的特殊字符?

Python:错误 - tabula-py 无法读取 PDF

python - 两个常量字符串之间的正则表达式匹配文本

python-2.7 - 从 unicode 字符串中转义字符

OpenCV2.4 python - 立体匹配和视差图

Python - SQLite JSON1 加载扩展

python - 用户选择的变量从列表中删除

python - urllib2 下载 HTML 文件