擅长:python、mysql、java
<p><strong>为什么当前代码失败?</strong></p>
<p><code>self</code>是<code>callback</code>的自由变量,如果您阅读<a href="https://docs.python.org/3.4/library/functions.html#locals" rel="nofollow noreferrer">^{<cd3>}</a>的文档,您将发现:</p>
<blockquote>
<p>Free variables are returned by <code>locals()</code> when it is called in function
blocks, but not in <strong>class blocks</strong>.</p>
</blockquote>
<p>现在从<a href="https://docs.python.org/3.4/library/functions.html#exec" rel="nofollow noreferrer">^{<cd4>}</a>的文档来看:</p>
<blockquote>
<p>If <code>exec</code> gets two separate objects as globals and locals, the code will
be executed as if it were embedded in a <strong>class definition</strong>.</p>
</blockquote>
<p>因此,当我们将两个不同的对象传递给<code>exec()</code>时,<code>locals()</code>字典对于<code>callback()</code>实际上是空的,因为它不能再访问自由变量,因此传递<code>locals()</code>和<code>globals()</code>的合并版本的<a href="https://stackoverflow.com/a/28951120/846892">solution suggested by @mgilson</a>应该为您做这件事。你知道吗</p>