此代码失败:
import setuptools.command
setuptools.command.install.install
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'install'
但这有效:
import setuptools.command.install
setuptools.command.install.install
<class setuptools.command.install.install at 0x7f2355911328>
其中install是setuptools的命令子模块的install子模块的类。
Setuptools的版本是2.2,但是我尝试了一个虚拟的python项目,并且得到了相同的行为,因此我不确定这是特定于setuptools的。
在Ubuntu升级后(从python 2.7.4升级到2.7.6),我注意到了这一点。我确信第一个代码片段确实可以在升级前工作,但是在python发行说明中找不到任何相关的内容。
奇怪的是,这与os软件包的行为似乎有所不同:
import os
os.path.join
<function join at 0x7f9f4be6fc80>
我的问题:使用其他程序包的子模块中的功能时,是否需要始终始终显式导入子模块?如果是这样,为什么这不影响os?否则,如何判断我是否需要这样做?
os.path
很特别 在os
模块,它注入os.path
到sys.modules
。参见https://github.com/python-git/python/blob/715a6e5035bb21ac49382772076ec4c630d6e960/Lib/os.py#L119
因此,通常,您始终需要导入子模块。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句