函数列表中附加了什么(func(x) 中的内容)
What does get to appended to the functions list (what's inside the func(x))
这段代码打印出[16,16,16,16,16].
functions = []
for i in range(5):
def func(x):
return x + i
functions.append(func)
for f in functions:
print(f(12))
在第一个 for 循环中,当 i
取值 3 时,追加到列表中的 func 中有什么? func(x):x+3
或 func(x):x+i
或 func(x): x+i where i=3
?
我假设答案是 func(x):x+i
,其中 i
在附加到列表时不采用任何实际值。有人可以使用框架、闭包和范围概念向我解释吗?当 i = 3
在父框架中时,为什么 func(x) 不附加为 x+3
?
使用默认参数:
functions = []
for i in range(5):
def func(x, a = i):
return x + a
functions.append(func)
for f in functions:
print(f(12))
这是有效的,因为默认值是在创建函数时计算的。否则所有函数将指向 i
.
的最后一个值
请随时查看 Late Binding Closures 了解更多相关信息。
Python’s closures are late binding. This means that the values of variables used in closures are looked up at the time the inner function is called.
Here, whenever any of the returned functions are called, the value of i is looked up in the surrounding scope at call time. By then, the loop has completed and i is left with its final value of 4.
指南中的示例使用 range(5)
,因此引用直接适用于您的函数。
另一个选项是高阶函数。
functions = []
for i in range(5):
def func_maker(i):
def _func(x):
return x + i
return _func
functions.append(func_maker(i))
for f in functions:
print(f(12))
这段代码打印出[16,16,16,16,16].
functions = []
for i in range(5):
def func(x):
return x + i
functions.append(func)
for f in functions:
print(f(12))
在第一个 for 循环中,当 i
取值 3 时,追加到列表中的 func 中有什么? func(x):x+3
或 func(x):x+i
或 func(x): x+i where i=3
?
我假设答案是 func(x):x+i
,其中 i
在附加到列表时不采用任何实际值。有人可以使用框架、闭包和范围概念向我解释吗?当 i = 3
在父框架中时,为什么 func(x) 不附加为 x+3
?
使用默认参数:
functions = []
for i in range(5):
def func(x, a = i):
return x + a
functions.append(func)
for f in functions:
print(f(12))
这是有效的,因为默认值是在创建函数时计算的。否则所有函数将指向 i
.
请随时查看 Late Binding Closures 了解更多相关信息。
Python’s closures are late binding. This means that the values of variables used in closures are looked up at the time the inner function is called.
Here, whenever any of the returned functions are called, the value of i is looked up in the surrounding scope at call time. By then, the loop has completed and i is left with its final value of 4.
指南中的示例使用 range(5)
,因此引用直接适用于您的函数。
另一个选项是高阶函数。
functions = []
for i in range(5):
def func_maker(i):
def _func(x):
return x + i
return _func
functions.append(func_maker(i))
for f in functions:
print(f(12))