Pinkie Pie
Pinkie Pie

Reputation: 71

Python - Why doesn't this instance method need parentheses when called inside another instance method?

I know it's a noob question, but I'm trying to figure out why "self.update_count", doesn't need parentheses when its called from the 'create_widget' method. I've been searching, but can't find out why.

Please help.

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

Upvotes: 3

Views: 196

Answers (3)

Konstantin Dinev
Konstantin Dinev

Reputation: 34905

This is not a function call but a reference storage inside a dictionary:

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

Most probably the Button object has the capability of calling this method upon certain interaction.

Upvotes: 1

user23743
user23743

Reputation:

It isn't called from that method. It's using a reference to the function, which the button will call later when it's clicked. You can think of it as a function's name being a reference to the code in that function; to call the function you apply the () operator.

Upvotes: 0

Fred Foo
Fred Foo

Reputation: 363627

self.update_count()

would be a call to the method, so

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

would store the result from the method in self.bttn. However,

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

without the parens stores the method itself in self.bttn. In Python, methods and functions are objects that you can pass around, store in variables, etc.

As a simple example of this, consider the following program:

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)

Upvotes: 2

Related Questions