全部导入 不全部导入
Import All Does Not Import All
这个import
声明:
from tkinter import *
不导入 tkinter.filedialog
。为什么没有?
通常,从 from <package> import *
导入的值取决于该包的 __init__
文件的 __all__
列表中指定的值。
无法导入 filedialog
意味着它不包含在 tkinter
__init__
文件的 __all__
列表中。
评估一个包是否'exports'一些子模块的快速方法是在import
它之后评估它是否具有__all__
属性。如果是,它将 return 可用的子模块,如果不是 Attribute Error
将被提出。
例如,对于 scipy
这样的包:
import scipy
print(scipy.__all__) # prints all contents.
tkinter
是一个包,当执行 from tkinter import *
时,它将导入 __init__.py
中为 tkinter
包定义的所有名称,以及仅模块和 tkinter
包的 __init__.py
中的 __all__
中定义的子包。
在我的 Python 3.4 中,tkinter/__init__.py
中没有定义 __all__
,因此它不会从其中导入任何模块(如 filedialog
)。
中有解释
The only solution is for the package author to provide an explicit index of the package. The import statement uses the following convention: if a package’s __init__.py
code defines a list named __all__
, it is taken to be the list of module names that should be imported when from package import * is encountered.
If __all__
is not defined, the statement from sound.effects import * does not import all submodules from the package sound.effects into the current namespace; it only ensures that the package sound.effects has been imported (possibly running any initialization code in __init__.py
) and then imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by __init__.py
.
这个import
声明:
from tkinter import *
不导入 tkinter.filedialog
。为什么没有?
通常,从 from <package> import *
导入的值取决于该包的 __init__
文件的 __all__
列表中指定的值。
无法导入 filedialog
意味着它不包含在 tkinter
__init__
文件的 __all__
列表中。
评估一个包是否'exports'一些子模块的快速方法是在import
它之后评估它是否具有__all__
属性。如果是,它将 return 可用的子模块,如果不是 Attribute Error
将被提出。
例如,对于 scipy
这样的包:
import scipy
print(scipy.__all__) # prints all contents.
tkinter
是一个包,当执行 from tkinter import *
时,它将导入 __init__.py
中为 tkinter
包定义的所有名称,以及仅模块和 tkinter
包的 __init__.py
中的 __all__
中定义的子包。
在我的 Python 3.4 中,tkinter/__init__.py
中没有定义 __all__
,因此它不会从其中导入任何模块(如 filedialog
)。
The only solution is for the package author to provide an explicit index of the package. The import statement uses the following convention: if a package’s
__init__.py
code defines a list named__all__
, it is taken to be the list of module names that should be imported when from package import * is encountered.If
__all__
is not defined, the statement from sound.effects import * does not import all submodules from the package sound.effects into the current namespace; it only ensures that the package sound.effects has been imported (possibly running any initialization code in__init__.py
) and then imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by__init__.py
.