[Tutor] Python functions are first-class citizens (was: dict.get() vs. dict.get)

Ben Finney ben+python at benfinney.id.au
Fri Aug 1 05:22:11 CEST 2014


memilanuk <memilanuk at gmail.com> writes:

> What is the difference between dict.get() and dict.get

The ‘foo()’ syntax calls ‘foo’.

‘dict.get’ is the function (an attribute of the ‘dict’ type), and you
can call that function by specifying parameters in parens ‘()’.

>             counts[words[1]] = counts.get(words[1], 0) + 1

This line is calling the ‘get’ method of the ‘counts’ object. Since that
object likely doesn't have its own ‘get’ attribute, this will be the
‘dict.get’ function (since ‘coutns’ is an instance of ‘dict’).

That part of the expression – ‘counts.get(words[1], 0)’ – will evaluate
to whatever is the return value of that call.

> max_key = max(counts, key=counts.get)

This specifies ‘counts.get’, without calling it. The expression
‘counts.get’ evaluates to that function object.

That value is then used as the value for the ‘key’ parameter when
calling ‘max’ here.

> So... the similarity between dict.get() and dict.get as used here is
> kinda confusing me.

I hope that helps. They are the same function; but the former is
*calling* the function object, and optionally using the return value;
the latter is referring to the function object *as* a value.

> Any pointers would be much appreciated.

This use of functions and other callable objects as values, is sometimes
referred to as the fact Python has “first-class functions”
<URL:http://en.wikipedia.org/wiki/First-class_function>.

-- 
 \      “What we usually pray to God is not that His will be done, but |
  `\                       that He approve ours.” —Helga Bergold Gross |
_o__)                                                                  |
Ben Finney



More information about the Tutor mailing list