<p><code>a_function = lambda x: do_something_with(x)</code></p>
<p>相当于</p>
<pre><code>def a_function(x):
return do_something_with(x)
</code></pre>
<p>在您的特定示例中,创建的函数是实例方法。例如,您可以编写:</p>
<pre><code>class Tests:
...
test_1_2 = lambda self: self.check(1, 2)
</code></pre>
<p>相当于:</p>
<pre><code>class Tests:
...
def test_1_2(self):
return self.check(1, 2)
</code></pre>
<p>现在,由于标识符是动态生成的,因此使用<code>setattr</code>。</p>
<hr/>
<blockquote>
<ol>
<li>Is the lambda used here to perform the exact opposite of <code>functools.partial()</code> (i.e. to create a wrapper function with one extra
parameter that is not yet known)</li>
</ol>
</blockquote>
<p>不,不是真的。实际上<code>partial</code>也可以在这里使用。</p>
<pre><code>test_1_2 = lambda self: self.check(1, 2)
</code></pre>
<p>会变成</p>
<pre><code>test_1_2 = partial(Tests.check, i=1, j=2)
</code></pre>
<blockquote>
<ol>
<li>Is self a meaningful keyword or would lambda spam would work just as well?</li>
</ol>
</blockquote>
<p>实例方法的第一个参数始终需要是实例。<strong>约定是命名参数<code>self</code>,但您可以使用任何其他名称。我不建议这样做,因为这会使你的代码更难阅读和理解。</p>
<blockquote>
<ol>
<li>What point is that lambda evaluated?</li>
</ol>
</blockquote>
<p><code>lambda</code>创建匿名函数,任何函数都是在调用时求值的。</p>
<blockquote>
<ol>
<li>How come the .check() is perfectly fine outside the classes scope?</li>
</ol>
</blockquote>
<p>不是。它是<code>self.check()</code>,其中<code>self</code>是<code>Tests</code>类的实例。</p>