【发布时间】:2017-02-23 01:10:33
【问题描述】:
我以这种方式创建了一个包pkg。
$ tree
.
└── pkg
├── foo.py
└── __init__.py
1 directory, 2 files
susam@debian1:~/so$ cat pkg/__init__.py
susam@debian1:~/so$ cat pkg/foo.py
print('executing module foo ...')
def bar():
print('bar')
以下所有 Python shell sn-ps 均来自单个交互式 与 Python 解释器的会话。我已将它们分成多个 块之间添加我自己的评论。
这是我的 Python 版本。
Python 3.4.2 (default, Oct 8 2014, 10:45:20)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
以下导入不会导入foo,因为__all__ 不是
在__init__.py 中定义。
>>> from pkg import *
>>> foo.bar()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
>>>
上述行为已在 Python 教程中描述 https://docs.python.org/3/tutorial/modules.html#importing-from-a-package.
如果
__all__没有定义,语句from sound.effects import *不会将包sound.effects中的所有子模块导入 当前命名空间;它只确保包sound.effects有 已导入(可能在__init__.py) 然后导入在 包。
以下仅导入 bar()。它不导入foo。
>>> from pkg.foo import bar
executing module foo ...
>>> bar()
bar
>>> foo.bar()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
但奇怪的是在上一次导入之后,下面的导入结束了
导入foo,即使__all__ 未在__init__.py 中定义。
>>> from pkg import *
>>> foo.bar()
bar
为什么会这样?
【问题讨论】:
标签: python package python-import python-3.6