<p><code>number</code>需要在全局范围内,这意味着在函数定义之外(不应该缩进)</p>
<p>如果变量在函数中,则无法在另一个文件中获取它</p>
<p>pack.py</p>
<pre class="lang-py prettyprint-override"><code>number = 100
def test():
test.other_number = 999 # here we assigne a variable to the function object.
print("test")
</code></pre>
<p>另一个</p>
<pre class="lang-py prettyprint-override"><code>import pack
pack.test()
print(pack.number)
print(test.other_number) # this only works if the function has been called once
</code></pre>
<p>或者,如果您正在使用类:</p>
<p>pack.py</p>
<pre class="lang-py prettyprint-override"><code>class Someclass():
other_number = 999 # here we define a class variable
def __init__(self):
self.number = 100 # here we set the number to be saved in the class
def test(self):
print(self.number) # here we print the number
</code></pre>
<p>另一个</p>
<pre class="lang-py prettyprint-override"><code>import pack
somclass_instance = pack.Someclass() # we make a new instance of the class. this runs the code in __init__
somclass_instance.test() # here we call the test method of Someclass
print(somclass_instance.number) # and here we get the number
print(Someclass.other_number) # here we retrieve the class variable
</code></pre>