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

Alan Gauld alan.gauld at yahoo.co.uk
Tue Jun 19 13:16:18 EDT 2018


On 19/06/18 16:52, C W wrote:
> Thank you all. I'm relatively new to OOP, I think that's where the problem
> is. It's different from C or any C alike language.

True, but even in C you can have pointers to functions
which work in a similar fashion.

> I'm still figuring out what's under the hood with OOP.

This particular feature has nothing to do with OOP,
it happens at the procedural level too.
Consider:

>>> aVar = 42
>>> aVar
42
>>> aVar()
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    aVar()
TypeError: 'int' object is not callable
>>> def aFunc(): return 66

>>> aFunc()
66
>>> aFunc
<function aFunc at 0x7ff377584950>
>>>

So using parens to access a variable yields an error,.
Using parens on a function is fine
Not using parens on a variable returns the value
Not using parens on a function returns the function

And finally:

>>> anotherVar = aFunc
>>> anotherVar
<function aFunc at 0x7ff377584950>
>>> anotherVar()
66
>>>

We make a variable reference a function.
Now the variable acts just like the function it
references.

That's because variables in Python are just names
that reference a value and the variable "acts" like
whatever kind of value it references.

But it has nothing to do with OOP. It is much
more fundamental than that.

-- 
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