A Python module and package loading confusion

我只是一个虾纸丫 提交于 2019-11-27 07:23:55

问题


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 babymodule.

Can someone explain me how this works?


回答1:


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


来源:https://stackoverflow.com/questions/16201068/a-python-module-and-package-loading-confusion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!