[Tutor] What's the difference between calling a method with parenthesis vs. without it?

Alan Gauld alan.gauld at yahoo.co.uk
Mon Jun 18 04:33:37 EDT 2018


On 17/06/18 19:02, C W wrote:
> I never figured out when to call a method with parenthesis, when is it not?

You call anything in Python (function, method, class, etc) using
parentheses. The parentheses are what makes it a call.

When you don't use parentheses you are referencing the
callable object.

>> data.isnull()

That calls the isnull method of data

>> data.isnull

That references the isnull method, so you could store it in a variable
for future use:

checkNull = data.isnull
# do other stuff.

if checkNull():  # call data.isnull() via the variable
   # do more stuff

> <bound method DataFrame.isnull of       number  air_pressure_9am

And thats what the return value says - its a method.

> air_temp_9am  avg_wind_direction_9am  \
> 0          0        918.060000     74.822000              271.100000

But I've no idea why you get this output...

> Obviously, the second case does not make any senses. 

The fact that its a method makes sense, the "data" makes no sense.


> But, in data.columns,
> it is only correct to do without parenthesis as below:
> 
>> data.columns
> 
> Index(['number', 'air_pressure_9am', 'air_temp_9am', 'avg_wind_direction_9am',

So data.columns is not a method but an attribute.
The attribute apparently references an Index object.

> # with parenthesis throws an error
>> data.columns()

We've already established that data.columns is a reference
to an Index object and you can't call an Index object,
it is not "callable"

        Traceback (most recent call
> last)<ipython-input-16-05cf52d0a56e> in <module>()----> 1
> data.columns()
> TypeError: 'Index' object is not callable

Which is what Python is telling you.

> I always thought columns(), isnull() are methods to objects, 

isnull is apparenmtly a method.
columns is apparenmtly an attribute.

They are different things and you need to read the
documentation (or code) to see which is which.
You can call a method.
You can only call an attribute if it stores a callable object.

And if you use a method name without parens you
get a reference to the method back.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list