是否可以在 python 中从文件夹/包中获取模块列表并导入它们?
我希望能够从类中的函数执行此操作,以便整个类都可以访问它们(可能通过 __init__
方法完成)。
如有任何帮助,我们将不胜感激。
最佳答案
参见 modules document .
The only solution is for the package author to provide an explicit index of the package. The import statement uses the following convention: if a package’s
__init__.py
code defines a list named__all__
, it is taken to be the list of module names that should be imported when from package import * is encountered. It is up to the package author to keep this list up-to-date when a new version of the package is released. Package authors may also decide not to support it, if they don’t see a use for importing * from their package. For example, the file sounds/effects/__init__.py
could contain the following code:__all__ = ["echo", "surround", "reverse"]
This would mean that from sound.effects import * would import the three named submodules of the sound package.
是的,您可以通过为目录中的文件列出目录并手动导入它们来找到执行此操作的方法。但是没有内置语法可以满足您的要求。
关于python - 在 Python 中导入模块的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7851321/