<p>您有三种选择:</p>
<ol>
<li>使用通配符导入所有内容(即<code>from filePaths import *</code>)</li>
<li>导入选定对象(即<code>from filePaths import object1, object2, object3 #...</code>)</li>
<li>使用点表示法(即<code>import filePaths</code>然后<code>filePaths.object1 #etc</code>)</li>
</ol>
<p>有些选项可能被认为是比其他选项更好的编程风格</p>
<p>通配符起作用的原因是,如果在import语句中列出了<code>filePaths</code>内创建的所有对象,则它与上面的选项2相同。通常,您应该只选择性地导入所需的方法和对象,或者只导入脚本并根据需要使用点表示法来选择性地使用方法和对象</p>
<p>下面的示例代码显示了如何使用点表示法</p>
<p>文件1:</p>
<pre><code># objects_to_import.py
bob = 127
string = 'my string'
def foo():
print('bar')
def bar():
print('foo')
def print_var(var):
print(var)
</code></pre>
<p>文件2:</p>
<pre><code># main.py in the same directory as objects_to_import.py
import objects_to_import
print(objects_to_import.bob)
objects_to_import.print_var(objects_to_import.bob)
objects_to_import.foo()
objects_to_import.bar()
try:
print(string)
except NameError:
print("You didn't import that variable or use correct notation!")
</code></pre>
<p>然后,运行main.py输出:</p>
<pre><code>"""
127
127
bar
foo
You didn't import that variable or use correct notation!
"""
</code></pre>
<p>如果改为main.py,则结果相同:</p>
<pre><code>from objects_to_import import bob, foo, bar, print_var
print(bob)
print_var(bob)
foo()
bar()
try:
print(string)
except NameError:
print("You didn't import that variable or use correct notation!")
</code></pre>
<p>请注意,如果我们将以下代码添加到main.py的两个版本中:</p>
<pre><code>if('bob' in globals()):
print('Bob is in your globals!')
else:
print("Can't find bob in your globals")
</code></pre>
<p>我们发现<code>bob</code>在显式导入时在全局空间中,但在使用点表示法和一般非显式导入语句时不存在。因此,选择一种导入方法而不是另一种导入方法可能有一些实际原因(例如,如果您的程序较长且复杂,并且希望更轻松地管理潜在的名称冲突,则应使用点表示法)</p>