Lambda 或 functools.partial 用于延迟函数评估?

lin*_*ndy 1 python lambda deferred-loading

假设我们有一个基本功能:

def basic(arg):
    print arg
Run Code Online (Sandbox Code Playgroud)

我们需要推迟在另一个函数中对该函数的求值。我正在考虑两种可能的方法:

  1. 使用 lambda:

    def another(arg):
        return lambda: basic(arg)
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用 functools.partial

    from functools import partial
        def another(arg):
            return partial(basic, arg)
    
    Run Code Online (Sandbox Code Playgroud)

首选哪种方法?为什么?还有另一种方法可以做到这一点吗?

enr*_*cis 6

Lambda 不存储不在其参数中的数据。这可能会导致奇怪的行为:

def lambdas(*args):
    for arg in args:
        yield lambda: str(arg)

one, two, three, four = lambdas(1, 2, 3, 4)
print one(), two(), three(), four()
Run Code Online (Sandbox Code Playgroud)

预期产出

1 2 3 4
Run Code Online (Sandbox Code Playgroud)

输出

4 4 4 4
Run Code Online (Sandbox Code Playgroud)

发生这种情况是因为 lambda 不存储arg值,而是遍历了 的所有元素args,所以 nowarg始终是4

首选方法是使用functools.partial,您必须在其中存储参数:

from functools import partial

def partials(*args):
    for arg in args:
        yield partial(str, arg)

one, two, three, four = partials(1, 2, 3, 4)
print one(), two(), three(), four()
Run Code Online (Sandbox Code Playgroud)

预期产出

1 2 3 4
Run Code Online (Sandbox Code Playgroud)

输出

1 2 3 4
Run Code Online (Sandbox Code Playgroud)