#!/usr/bin/env python3# -*- coding: utf-8 -*-' a test module '
__author__ = 'Zhang Shuai'defoperator():return [lambda n: n * m for m in range(6)]
print([o(3) for o in operator()])
# 这是由于闭包函数引用的外部作用域的*变量, 只有在内部函数被调用的时候才会搜索变量m的值, 由于循环已结束, m指向最终值5, 所以各函数调用都得到了相同的结果。# 即:defoperator():return [lambda m: 5 * n,lambda m: 5 * n,lambda m: 5 * n,lambda m: 5 * n,lambda m: 5 * n,lambda m: 5 * n]
# 等价于defoperator2():
l = []
for i in range(6):
deffunc(m):return m * i
l.append(func)
return l
print([o(3) for o in operator2()])
# 改进defoperator3():return [lambda n, m=m: n * m for m in range(6)]
print([o(3) for o in operator3()])
# 这就相当于给每个函数一个默认参数# 即:# def operator3():# return [lambda n, m=0: m * n, lambda n, m=1: m * n, lambda n, m=2: m * n, lambda n, m=3: m * n,# lambda n, m=4: m * n, lambda n, m=5: m * n]defoperator4():
l = []
for i in range(6):
deffunc(m, i=i):return m * i
l.append(func)
return l
print([o(3) for o in operator4()])