擅长:python、mysql、java
<p>这里不需要使用<code>global</code>。在您的示例中,<code>chosen</code>和{<cd3>}是类属性。而不是:</p>
<pre><code>global chosen
chosen = self.choice
</code></pre>
<p>你只要写下:</p>
^{pr2}$
<p>在类之前定义<code>chosen2</code>时,实际上是在<code>global</code>所指的范围内定义它。当您在类范围内定义它时,它是一个由所有实例共享的类属性。在</p>
<p><em>更新:</em>如前所述,直接赋值给class属性不是您想要的,因为它将在实例上创建一个新属性,该属性将在类上屏蔽它。但在您的<code>Listener2</code>示例中,这是可以的:</p>
<pre><code>def actionPerformed(self, event):
self.chosen[self.choice] = event
</code></pre>
<p>在这里,您没有重写<code>.chosen</code>,而是将一个项添加到它所引用的字典中,这样类将为每个侦听器保存最新事件的记录。在</p>