擅长:python、mysql、java
<p>您可以将Python全局变量看作“模块”变量,因此它们比C语言中传统的“全局变量”要有用得多</p>
<p>全局变量实际上是在模块的<code>__dict__</code>中定义的,可以作为模块属性从该模块外部访问。</p>
<p>所以,在你的例子中:</p>
<pre><code># ../myproject/main.py
# Define global myList
# global myList - there is no "global" declaration at module level. Just inside
# function and methods
myList = []
# Imports
import subfile
# Do something
subfile.stuff()
print(myList[0])
</code></pre>
<p>以及:</p>
<pre><code># ../myproject/subfile.py
# Save "hey" into myList
def stuff():
# You have to make the module main available for the
# code here.
# Placing the import inside the function body will
# usually avoid import cycles -
# unless you happen to call this function from
# either main or subfile's body (i.e. not from inside a function or method)
import main
main.mylist.append("hey")
</code></pre>