廖学峰PYTHON 返回函数疑问

def count():
    fs = []
    for i in range(1, 4):
        def f():
             return i*i
        fs.append(f)
    return fs

f1, f2, f3 = count()
>>> f1()
9
>>> f2()
9
>>> f3()
9

为何结果是9,9,9不是1,4,9?


解答:

count函数运行完以后,

fs = [f, f, f]

f1, f2, f3 = count()

相当于

[f1, f2, f3] = [f, f, f]

相当于

f1 = f

f2 = f

f3 = f

f函数返回的是i的平方,i是3,所以返回9, 9, 9


你可能感兴趣的:(python)