简体   繁体   English

如何导入文件夹中的所有 python 类?

[英]how can I import all python classes in a folder?

This is the current structure of my project.这是我项目的当前结构。

   cities
       newyork.py
       london.py
       berlin.py
   main.py
   requirements.txt

Each of the city files contains a class. For instance Class Newyork: is defined in newyork.py每个城市文件都包含一个 class。例如Class Newyork:newyork.py中定义

In my main.py I am importing all the classes for use in this manner:在我的main.py ,我导入了所有以这种方式使用的类:

from cities.newyork import NewYork
from cities.london import London
from cities.berlin import Berlin

What I would like: To have something like this我想要什么:拥有这样的东西

from cities.* import NewYork, London, Berlin.

Is this possible in python?这在 python 中可能吗?

Add the following to cities/__init__.py (creating the file if necessary):将以下内容添加到cities/__init__.py (必要时创建文件):

from newyork import NewYork
from london import London
from berlin import Berlin

Then you can write然后你可以写

from cities import NewYork, London, Berlin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获取从 Python 3 中的模块导入的所有类的列表? - How can I get a list of all classes I import from a module in Python 3? 如何将 python py 文件中的所有类导入另一个 py 文件中的另一个 class? - how can I import ALL classes in a python py file to another class in another py file? 我可以一次从一个文件夹中导入所有 Python 文件吗? - Can I import all Python files from a folder at once? 如何将多个文件夹层次结构中的所有 python 文件导入单个 pyinstaller 可执行文件? - How can I import all my python files in multiple folder hierarchy into a single pyinstaller executable? Python:如何导入所有变量? - Python: How can I import all variables? Python:如何将python模块安装到某个文件夹中并将其导入 - Python: How can I install a python module into a certain folder and import it 在Python中,如何从具有相对路径的祖父母文件夹中导入? - In Python, how can I import from a grandparent folder with a relative path? 如何使用 python 导入包含图像的文件夹 - how can i import a folder containing images with python 如何从 python 中的另一个文件夹导入 csv? - How can I import a csv from another folder in python? Python-从包中导入所有类时是否可以导入特定类 - Python - Can I import specific classes when importing all from a package
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM