from a.b.c.d import m

假如a是一个package, 那么这段代码会执行哪些代码呢?下面是一个例子:

首先看目录结构

.
├── a.py
└── test
    ├── __init__.py
    └── h
        ├── __init__.py
        ├── h.py
        └── x
            ├── __init__.py
            └── y
                └── __init__.py

a.test.h.x.y.__init__.py

print("test.h.x.y__init__.py is running :", __name__)
NIHAO = "hello from y"

a.py

from test.h.x.y import NIHAO

执行a.py的结果如下:

test.__init__.py is running : test
test.h.__init__.py is running : test.h
test.h.x.__init__.py is running : test.h.x
test.h.x.y__init__.py is running : test.h.x.y

同时还可以看到 __name__代表着什么。

也就是说,import导入某个包的时候,会由外而内的依次执行各自包下面的init.py。为了避免循环导入的问题,在自己写的包里面import自己包里的内容使用相对路径,由内而外的去寻找就不会导致循环导入了

打赏作者

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

CAPTCHA