user3477465
user3477465

Reputation: 193

What is the difference between using parenthesis and not using parenthesis in a method in Python

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

Answers (3)

furas
furas

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

David Young
David Young

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

hakki
hakki

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

Related Questions