def count():
fs = []
for i in range(1, 4):
def f(j):
def g():
return j*j
return g
r = f(i)
fs.append(r) #fs作为列表,为什么可以append(r)?(而r是f所返回的函数)
return fs #个人的想法应该是fs.append(r())
f1, f2, f3 = count()
print f1(), f2(), f3()
想弄明白的是:这里传入append的r是以什么形式传入的呢
谢谢各位指教:D
is passed in in the form of a function definition, similar to delayed calling, which is not obvious in your example,
You can think of r in return r in the function as a variable, but this variable saves the definition of the function.
The actual call to the function is through x() later
r is an object, and the type of this object is a function.
In other words, r is an object of type function, like
1 is an object of type integer
'hi' is the same as an object of type string
If you change it to
fs.append(r())
, it is also possible, but the meaning of the function is different. After executing thecount()
function, it will return the result[1, 4, 9]
, and you can no longer useprint f1(), f2(), f3()
to print out the results because:fs.append(r())
也是可以的,但是函数意义就不同了,执行count()
函数后其会返回结果[1, 4, 9]
,而不能再使用print f1(), f2(), f3()
打印出结果,原因在于:注意这里是
Note that this isg
不是g()
,所以执行count()
返回的其实是[g1, g2, g3]
一个包含三个闭包函数的列表,每个闭包函数绑定的自由变量不同(分别是1, 2, 3),因此将这个列表解包给f1, f2, f3
后,执行print f1(), f2(), f3()
相当于执行三个函数后并打印出结果,因此最终输出1, 4, 9
rrreeeg
notg()
, so what is returned by executingcount()
is actually[g1, g2, g3]
A list containing three closure functions. Each closure function binds different free variables (respectively 1, 2, 3), so unpack this list tof1, f2, f3
, executingprint f1(), f2(), f3()
is equivalent to executing three functions and printing out the results, so the final output is1, 4, 9🎜
f1 = fs[0] = r = g
f1 = fs[0] = r = g
所以才能
That’s why 🎜 🎜f1()
f1()
🎜