Python为什么这个实例方法在另一个实例方法内部调用时不需要括号?

2024-03-28 23:09:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道这是个无足轻重的问题,但我想弄清楚原因。”self.update_计数“”从“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()

Tags: theselfandefcountcreatecounterupdate
1条回答
网友
1楼 · 发布于 2024-03-28 23:09:50
self.update_count()

是对方法的调用,所以

^{pr2}$

将方法的结果存储在self.bttn中。但是

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

没有parens,方法本身就存储在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)
网友
2楼 · 发布于 2024-03-28 23:09:50

这不是函数调用,而是字典中的引用存储:

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

最有可能的是,按钮对象具有在特定交互时调用此方法的能力。在

网友
3楼 · 发布于 2024-03-28 23:09:50

它不是从该方法调用的。它使用了对函数的引用,当单击该函数时按钮将调用该函数。您可以将其视为函数名,它是对该函数中代码的引用;要调用该函数,需要应用()运算符。在

相关问题 更多 >