为什么'import x; x.y'与'from x import y'的行为不同,第一个在package x .__ init__未完成时失败? [英] Why does 'import x;x.y' behave different from 'from x import y', and the first one fails when package x.__init__ is not completed?
问题描述
为什么'import ...'和'from ... import ...'之间存在差异?为什么我使用第一个获得异常?
Why is there a difference between 'import ...' and 'from ... import ...' and why do I get an exception using the first one?
这是我的布局:
/tmp/zero/
|~two/
| |-__init__.py
| |-four.py
| `-three.py
|-__init__.py
`-one.py
/tmp/zero/one.py
=================
import zero.two
/tmp/zero/two/__init__.py
=================
import zero.two.three
/tmp/zero/two/three.py
=================
# this works
from zero.two import four
four.myprint()
# this FAILS
import zero.two.four
zero.two.four.myprint()
/tmp/zero/two/four.py
=================
def myprint():
print 'four.myprint'
/tmp$ PYTHONPATH=/tmp/ python -c 'import zero.one'
four.myprint
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "zero/one.py", line 1, in <module>
import zero.two
File "zero/two/__init__.py", line 1, in <module>
import zero.two.three
File "zero/two/three.py", line 9, in <module>
zero.two.four.myprint()
AttributeError: 'module' object has no attribute 'two'
推荐答案
zero.two
是一个模块,零/两个/ __ init__的.py
。这是具体的事情,而不是一件神奇的事情。如果你输入零/两/ __ init __。py
一行。导入四个
,它将开始工作。 os.path
就是一个例子 - 它是一个模块,但它是在 os / __ init __。py
中导入的,所以你可以 import os; os.path
。
zero.two
is a module there, zero/two/__init__.py
. It's a concrete thing, not a magic thing. If you put into zero/two/__init__.py
a line from . import four
, it'll start working. os.path
is an example of this - it's a module, but it's imported in os/__init__.py
so that you can import os; os.path
.
这篇关于为什么'import x; x.y'与'from x import y'的行为不同,第一个在package x .__ init__未完成时失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!