51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

Python Lambda

Lambda 无法捕获循环中的临时变量,如 test01 函数的例子。如果想要捕获循环中的临时变量,可以使用 test02 闭包函数、test03 类封装、test04 partial 函数中的方式。

from functools import partial

def test01():

def task(number):
    print('task:', id(number), number)

func_list = []
for number in range(10):
    print('for: ', id(number), number)
    # lambda 绑定的是局部变量的引用,而不是引用的值
    func_list.append(lambda: task(number))

for func in func_list:
    func()

def test02():

def wrapper(number):
    def task():
        print('task:', id(number), number)
    return task

func_list = []
for number in range(10):
    print('for: ', id(number), number)
    func_list.append(wrapper(number))

for func in func_list:
    func()

def test03():

class wrapper:

    def __init__(self, func, param):
        self.func = func
        self.param = param

    def __call__(self):
        return self.func(self.param)


def task(number):
    print('task:', id(number), number)

func_list = []
for number in range(10):
    print('for: ', id(number), number)
    func_list.append(wrapper(task, number))

for func in func_list:
    func()

def test04():

def task(number):
    print('task:', id(number), number)

func_list = []
for number in range(10):
    print('for: ', id(number), number)
    func_list.append(partial(task, number))

for func in func_list:
    func()

if name == 'main': # test01() # test02() # test03() test04()

赞(7)
未经允许不得转载:工具盒子 » Python Lambda