[Tutor] What's the difference between calling a method with parenthesis vs. without it?
Steven D'Aprano
steve at pearwood.info
Mon Jun 18 06:12:36 EDT 2018
On Sun, Jun 17, 2018 at 02:02:07PM -0400, C W wrote:
> Dear Python experts,
>
> I never figured out when to call a method with parenthesis, when is it not?
> It seems inconsistent.
You *always* CALL a method (or function) with parentheses.
But sometimes you can grab hold of a method (or function) *without*
calling it, by referring to its name without parentheses.
The trick is to understand that in Python, functions and methods are
what they call "First-class citizens" or first-class values, just like
numbers, strings, lists etc.
https://en.wikipedia.org/wiki/First-class_citizen
Let's take a simple example:
def add_one(x=0):
return x + 1
To CALL the function, it always needs parentheses (even if it doesn't
require an argument):
py> add_one(10)
11
py> add_one()
1
But to merely refer to the function by name, you don't use parentheses.
Then you can treat the function as any other value, and print it, assign
it to a variable, pass it to a different function, or stick it in a
list. Anything you can do with anything else, really.
For example:
py> myfunction = add_one # assign to a variable
py> print(myfunction)
<function add_one at 0xb78ece84>
py> L = [1, "a", add_one, None] # put it inside a list
py> print(L)
[1, 'a', <function add_one at 0xb78ece84>, None]
If it isn't clear to you why anyone would want to do this in the first
place, don't worry too much about it, it is a moderately advanced
technique. But it is essential for such things as:
- function introspection;
- callback functions used in GUI programming;
- functional programming;
etc. For example, you may have seen the map() function. Here it is in
action:
py> list(map(add_one, [1, 10, 100, 1000]))
[2, 11, 101, 1001]
Can you work out what it does? If not, try opening the interactive
interpreter, and enter:
help(map)
and see if that helps.
Or ask here :-)
--
Steve
More information about the Tutor
mailing list