def count ():
fs = []
for i in range (1, 4):
def f ():
return i*i
fs.append(f())
print(fs)
return fs
a,b,c = count()
print(a)
print(b)
print(c)
#输出:
[1]
[1, 4]
[1, 4, 9]
1
4
9
def count ():
fs = []
for i in range (1, 4):
def f ():
return i*i
fs.append(f)
print(fs)
return fs
a,b,c = count()
print(a())
print(b())
print(c())
#输出:
[<function count.<locals>.f at 0x03884270>]
[<function count.<locals>.f at 0x03884270>, <function count.<locals>.f at 0x03884108>]
[<function count.<locals>.f at 0x03884270>, <function count.<locals>.f at 0x03884108>, <function count.<locals>.f at 0x03884150>]
9
9
9
以上两段代码有何不同?
code1 为函数调用
code2 为返回函数,闭包典型案例