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

Mats Wichmann mats at wichmann.us
Mon Jun 18 10:50:24 EDT 2018


On 06/17/2018 12:02 PM, C W wrote:
> Dear Python experts,
> 
> I never figured out when to call a method with parenthesis, when is it not?
> It seems inconsistent.
> 
> For example,
> If I do
> 
>> data.isnull()
> 
> numberair_pressure_9amair_temp_9amavg_wind_direction_9amavg_wind_speed_9am
> max_wind_direction_9ammax_wind_speed_9amrain_accumulation_9am
> rain_duration_9amrelative_humidity_9amrelative_humidity_3pm
> 0 False False False False False False False False False False False
> 1 False False False False False False False False False False False
> 2 False False False False False False False False False False False
> 
> Or I can do without parenthesis,
>> data.isnull
> 
> <bound method DataFrame.isnull of       number  air_pressure_9am
> air_temp_9am  avg_wind_direction_9am  \
> 0          0        918.060000     74.822000              271.100000
> 1          1        917.347688     71.403843              101.935179
> 2          2        923.040000     60.638000               51.000000
> 
> 
> Obviously, the second case does not make any senses. 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',
>        'avg_wind_speed_9am', 'max_wind_direction_9am', 'max_wind_speed_9am',
>        'rain_accumulation_9am', 'rain_duration_9am', 'relative_humidity_9am',
>        'relative_humidity_3pm'],
>       dtype='object')
> 
> 
> # with parenthesis throws an error
>> data.columns()

I think you've already got all you need, let me just try one more brief
summary, in case it helps - Python is not like certain other languages.

1. a def statement is a runnable statement that creates an object (class
statements are also runnable and also create an object)
2. you can only call objects that are callable (you have already seen
the error you get if you try)
3. you call by using the () syntax
4. you can refer to an object by a name bound to it without calling it.
IF you do so in a context that implies you are "printing" it, Python
will invoke a special method (called __repr__) to attempt to create a
human-readable representation of the object.  I only mention that
because what it prints out may not be what you expect - but you should
know that what is printing is a transformation of object -> helpful
string.  Try some experiments with this to get comfortable.









More information about the Tutor mailing list