Reputation: 193
d=dict(a=1)
What is the difference between the following two?
d.clear
d.clear()
Why can't the first clear the dictionary?
Upvotes: 0
Views: 108
Reputation: 142681
With ()
you execute function. Without ()
you get reference to function - and you can assign this to variable and execute later with new name.
new_d = d.clear # assign
new_d() # execute
BTW: in Ruby and Perl you can call function without parenthesis.
Upvotes: 1
Reputation: 10793
The first one doesn't actually call the function. In Python, you can use functions as values, so you can assign a function to a new variable like this:
def timeTen(n):
return n * 10
fn = timesTen
then you can call it later:
print(fn(5)) # 50
Functions are just values that just happen to have a certain property (that you can call them).
Upvotes: 1
Reputation: 6519
Using parenthesis calls the function where as not using them creates a reference to that function.
See below:
>>> def t():
... return "Hi"
...
>>> a = t
>>> a
<function t at 0x01BECA70>
>>> a = t()
>>> a
'Hi'
>>>
Here is a good link to explain further: http://docs.python.org/2/tutorial/controlflow.html (scroll down to the "defining functions" part).
Upvotes: 5