一个 Python 模块和包加载混淆 [英] A Python module and package loading confusion
问题描述
假设我有这样的事情:
<前>.├── 运行.py└── 测试├── __init__.py├── 模型│ ├── foo│ │ ├── baby.py│ │ └── __init__.py│ ├── __init__.py│ └── user.py└── start.py运行.py
从测试导入开始
start.py
from .models 导入用户
用户.py
来自 .进口富打印(foo.baby.Baby)
baby.py
Baby = "我是个婴儿"
现在,当您运行 run.py
文件时...
但是,如果您像这样更改 start.py
:
from .models.foo import baby从 .models 导入用户
一切正常.
当 start.py
中的 baby
模块没有提前加载时,foo
包对象没有对它的引用(foo.baby.Baby
抛出一个 AttributeError
).但是当我在 start.py
中加载 baby
模块时,foo
包对象自动获得了对 baby
的引用模块.
有人可以解释一下这是如何工作的吗?
子模块在导入之前不会自动成为包的属性.
您需要先导入test.models.foo.baby
first,然后foo.baby.Baby
才能工作.您可以在 foo/__init__.py
文件中执行此操作:
来自 .进口宝贝
Let's say I have something like this:
. ├── run.py └── test ├── __init__.py ├── models │ ├── foo │ │ ├── baby.py │ │ └── __init__.py │ ├── __init__.py │ └── user.py └── start.py
run.py
from test import start
start.py
from .models import user
user.py
from . import foo
print(foo.baby.Baby)
baby.py
Baby = "I am a baby"
Now, when you run the run.py
file...
>>> python run.py
... traceback ...
AttributeError: 'module' object has no attribute 'baby'
But, if you change the start.py
like this:
from .models.foo import baby
from .models import user
everything works correctly.
When the baby
module in start.py
wasn't loaded earlier, the foo
package object did not have a reference to it (foo.baby.Baby
threw an AttributeError
). But when I loaded the baby
module in start.py
, the foo
package object automatically got a reference to baby
module.
Can someone explain me how this works?
Submodules are not automatically attributes of a package until imported.
You need to import test.models.foo.baby
first before foo.baby.Baby
works. You can do this in the foo/__init__.py
file:
from . import baby
这篇关于一个 Python 模块和包加载混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!