B
B
Bjornie2017-07-27 19:57:02
Python
Bjornie, 2017-07-27 19:57:02

How does this closure work (according to Lutz's book)?

Please help me understand how this code works.
I wrote in the comments how I understand this code, but I don’t understand why the function works by passing only the argument N , and the action function returns exponentiation without an explicitly specified argument X . Where does she get it from?

def maker(N):
  def action(X):
    return X ** N
  return action

a = maker(2) # 1-й вызов, присваивание объекта функции maker переменной a, передача аргументу N значение "2"

print(a)
>>> <function maker.<locals>.action at 0x0000018DFFA2BA60>

print(a(3)) # 2-й вызов, аргумент N равен 3, т.е. функция action возвращает 3 ** 2. Почему тройка идет как X?
>>> 9

print(a(4))
>>> 16 # и т.д.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
PythonDeveloper, 2017-07-28
@PythonDeveloper

The task of the outer function is to return the inner one with the inner argument substituted into the body, passed to the outer one. When binding the variable a with the result of the work of the external function, the internal function created by the external one will be associated with a. As N, it will already have the value passed earlier to the external.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question