擅长:python、mysql、java
<p><code>global</code>都没有你认为的那样。在这两种情况下,<code>chosen</code>和{<cd3>}都是<em>类</em>变量,而不是全局变量。在</p>
<p>但是当您将<code>chosen</code>声明为全局变量并分配给它时,python很高兴地创建了一个全局变量(与<code>Listener1.chosen</code>分开)并存储了您的值。在</p>
<p>但是对于<code>chosen2</code>您没有给它赋值;您试图将它当作dict来处理,但是您没有通过赋值创建变量,因此失败了。在</p>
<p>您希望使用<code>self.chosen2</code>;作为一个类变量,<code>Listener2</code>的所有实例都可以使用它。您也可以使用<code>Listener2.chosen2</code>。对于<code>chosen</code>,可以使用<code>Listener1.chosen</code>来引用它。可以完全删除<code>global</code>关键字。在</p>
<p>在任何情况下,将变量声明为<code>global</code>并不意味着<em>超出了我当前的作用域</em>。它的意思是<em>在模块范围</em>,所以总是在函数、类和方法定义之外。在</p>