Ci-dessous, les différences entre deux révisions de la page.
Prochaine révision | Révision précédente | ||
python:modules_packages_import [2020/11/28 07:29] marclebrun créée |
python:modules_packages_import [2021/05/15 06:52] (Version actuelle) |
||
---|---|---|---|
Ligne 5: | Ligne 5: | ||
[[https://towardsdatascience.com/learn-python-modules-and-packages-in-5-minutes-bbdfbf16484e]] | [[https://towardsdatascience.com/learn-python-modules-and-packages-in-5-minutes-bbdfbf16484e]] | ||
+ | [[https://stackoverflow.com/questions/8953844/import-module-from-subfolder]] | ||
+ | |||
+ | <code>add __init__.py to every subfolder you are importing from</code> | ||
+ | |||
+ | |||
+ | ===== Exemple 1 ===== | ||
+ | |||
+ | <code python> | ||
+ | #/home/marc/test | ||
+ | ├── # app | ||
+ | │ ├── # controllers | ||
+ | │ │ ├── # a.py | ||
+ | │ │ │ | ||
+ | │ │ │ class ControllerA: | ||
+ | │ │ │ def hello(self): | ||
+ | │ │ │ print("Hello, I'm Controller A") | ||
+ | │ │ │ | ||
+ | │ │ └── # b.py | ||
+ | │ │ | ||
+ | │ │ class ControllerB: | ||
+ | │ │ def hello(self): | ||
+ | │ │ print("Hello, I'm Controller B") | ||
+ | │ │ | ||
+ | │ ├── # main.py | ||
+ | │ │ | ||
+ | │ │ from .controllers.a import ControllerA | ||
+ | │ │ from .controllers.b import ControllerB | ||
+ | │ │ | ||
+ | │ │ class Application: | ||
+ | │ │ def __init__(self): | ||
+ | │ │ self.name = "Mauricette" | ||
+ | │ │ | ||
+ | │ │ def show(self): | ||
+ | │ │ a = ControllerA() | ||
+ | │ │ a.hello() | ||
+ | │ │ b = ControllerB() | ||
+ | │ │ b.hello() | ||
+ | │ │ | ||
+ | │ └── # __init__.py | ||
+ | │ | ||
+ | │ from .main import Application | ||
+ | │ | ||
+ | │ app = Application() | ||
+ | │ | ||
+ | └── # run.py | ||
+ | |||
+ | from app import app | ||
+ | |||
+ | if __name__ == "__main__": | ||
+ | print(app.name) | ||
+ | app.show() | ||
+ | </code> | ||