Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Closure function
#2
A function definition creates both a variable name and a value in the current namespace
>>> def multiplier(x):
...     return x * n
... 
>>> multiplier
<function multiplier at 0x7f2ace916e18>
You see that the function definition creates the variable named 'multiplier' and this variable has a value which is a 'function object'.

In your code, the return multiplier returns this function object to the calling environment and this returned value is caught by the variable times3 in the assignment statement times3 = make_multiplier_of(3). This is how python remembers the function.

The function object contains a compiled version of the body code (a 'code object') and this is how python is able to execute the function later.

The function object can be passed around like any other python object. For example you could write
foobarbaz722 = times3
print(foobarbaz722(10))
Reply


Messages In This Thread
Closure function - by Uchikago - Jul-11-2019, 09:06 AM
RE: Closure function - by Gribouillis - Jul-11-2019, 10:21 AM
RE: Closure function - by Uchikago - Jul-11-2019, 10:36 AM
RE: Closure function - by Gribouillis - Jul-11-2019, 11:03 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020