一:函数作为返回值
>>> def lazy_sum(*args): ... def sum(): ... ax = 0 ... for n in args: ... ax = ax + n ... return ax ... return sum ... >>> f=lazy_sum(1,2,3,4,5) >>> >>> f <function sum at 0x7fd1b3eccaa0> >>> f() 15 >>> f1=lazy_sum(1,2,3,4,5) >>> f1() 15 >>>
二:闭包
>>> def count(): ... fs=[] ... for i in range(1,4): ... def f(): ... return i*i ... fs.append(f) ... return fs ... >>> f1, f2, f3 = count() >>> f1 <function f at 0x7fd1b3edfed8> >>> f1() 9 >>> f2() 9 >>> f3() 9 >>>
时间: 2024-10-06 17:17:41