python 延迟绑定(late binding)

时间:2022-11-15 22:46:40
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

' a test module '

__author__ = 'Zhang Shuai'


def operator():
    return [lambda n: n * m for m in range(6)]

print([o(3) for o in operator()])


# 这是由于闭包函数引用的外部作用域的*变量, 只有在内部函数被调用的时候才会搜索变量m的值, 由于循环已结束, m指向最终值5, 所以各函数调用都得到了相同的结果。
# 即:
def operator():
   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]

# 等价于
def operator2():
    l = []
    for i in range(6):
        def func(m):
            return m * i

        l.append(func)
    return l

print([o(3) for o in operator2()])





# 改进
def operator3():
    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]

def operator4():
    l = []
    for i in range(6):
        def func(m, i=i):
            return m * i

        l.append(func)
    return l

print([o(3) for o in operator4()])