Why does 'import x;x.y' behave different f

2019-07-15 02:16发布

Why is there a difference between 'import ...' and 'from ... import ...' and why do I get an exception using the first one?

Here is my layout:

/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'

标签: python import
1条回答
别忘想泡老子
2楼-- · 2019-07-15 03:00

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.

查看更多
登录 后发表回答