Eine Verwirrung beim Laden von Python-Modulen und Paketen
Nehmen wir an, ich habe so etwas:
. ├── 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"
Nun, wenn Sie das ausführenrun.py
Datei...
>>> python run.py
... traceback ...
AttributeError: 'module' object has no attribute 'baby'
Aber wenn du das änderststart.py
so was:
from .models.foo import baby
from .models import user
alles funktioniert einwandfrei.
Wenn derbaby
Modul instart.py
wurde nicht früher geladen, diefoo
Paketobjekt hatte keinen Verweis darauf (foo.baby.Baby
warf einAttributeError
). Aber als ich die geladen habebaby
Modul instart.py
, dasfoo
Paketobjekt hat automatisch einen Verweis aufbaby
Modul.
Kann mir jemand erklären, wie das geht?