Note that when using from package import item, the item can be either
a submodule (or subpackage) of the package, or some other name defined
in the package, like a function, class or variable. The import
statement first tests whether the item is defined in the package; if
not, it assumes it is a module and attempts to load it. If it fails to
find it, an ImportError exception is raised.
使用单个导入时,您遇到的实际问题是由于packages的优先级高于模块:
无论如何,我建议重命名文件或目录,因为您不能用给定的名称导入多个模块。出现此问题的原因是每个模块/包对象都存储在
sys.modules
中,这是一个简单的dict
,因此不能包含多个相等的键。特别是,假设
foo.py
和foo
目录位于不同的目录中(如果它们不在,则仍然无法导入foo.py
),执行以下操作时:它将加载
foo.py
,并将模块放入sys.modules
,然后尝试执行以下操作:将失败,因为导入尝试使用模块
foo.py
而不是包。如果您首先导入
foo.bar
,则会发生相反的情况;导入将使用包而不是模块。我很确定这不是您应该做的,但是您可以使用imp强制Python将特定文件作为模块导入:
现在你可以:
相关问题 更多 >
编程相关推荐