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

Peter Otten __peter__ at web.de
Mon Jun 18 04:46:26 EDT 2018


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. 

Let's try with our own class:

>>> class A:
...     def foo(self): return "bar"
... 
>>> a = A()
>>> a.foo()
'bar'

With parens the foo method is executed and returns the expected result whose 
repr() is then printed by the interactive interpreter.

>>> a.foo
<bound method A.foo of <__main__.A object at 0x7f0956a00eb8>>

Without parens the repr() of the method is printed just like the repr of any 
other value would be.

That repr() has the form 

<bound method CLASSNAME.METHODNAME REPR_OF_INSTANCE>

and in your case REPR_OF_INSTANCE happens to be a lengthy dump of the 
DataFrame. To verify our findings let's define a custom __repr__ for out A:

>>> class A:
...     def foo(self): return "bar"
...     def __repr__(self): return "yadda " * 10
... 
>>> A().foo
<bound method A.foo of yadda yadda yadda yadda yadda yadda yadda yadda yadda 
yadda >





More information about the Tutor mailing list