为了回应您对 Adam 的回答的评论,关于 10 个类有 10 个导入,首先不要忘记,Python 中的每个模块不需要一个类。模块应该按功能进行组织,因此您可以将相关的类分组到单个文件中(如果有意义的话)。
如果您仍然想让所有类一次性导入,您可以使用 from submodule import Class 语法将它们全部导入到 __init__.py 文件本身中,然后只需导入包含模块 - import mainmodule 并引用 mainmodule.Class1 等,甚至使用 from mainmodule import Class1, Class2, Class3 导入类直接添加到您的命名空间中并直接引用它们。
In response to your comment to Adam's answer, regarding having 10 imports for 10 classes, firstly don't forget that there's no need to have one class per module in Python. Modules should be organised by functionality, so you can group related classes in a single file if that makes sense.
If you still wanted to make all the classes importable in one go, you could import them all in the __init__.py file itself using the from submodule import Class syntax, then just import the containing module - import mainmodule and refer to mainmodule.Class1 etc, or even use from mainmodule import Class1, Class2, Class3 to import the classes directly into your namespace and refer to them directly.
Adam Bernier provides a good technical description of how packages work. A great description of how to arrange and ship a project is described in http://jcalderone.livejournal.com/39794.html
发布评论
评论(3)
将空的
__init__.py
文件放入 Models 目录中。然后,在您的应用程序中;大概上一层,您可以像这样引用 Models 目录中的模块:
并对其执行如下操作:
您还可以使用
from
关键字,如下所示:并像这样引用:
如果您只需要一个模块中的方法,您也可以这样做:
指向文档的强制链接。
Put an empty
__init__.py
file in the Models directory.Then, in your app; presumably one level up, you reference modules in the Models directory like this:
and do something with it like this:
You can also use the
from
keyword like this:and reference like this:
If you only need one method from a module, you could also do this:
Obligatory link to the documentation.
为了回应您对 Adam 的回答的评论,关于 10 个类有 10 个导入,首先不要忘记,Python 中的每个模块不需要一个类。模块应该按功能进行组织,因此您可以将相关的类分组到单个文件中(如果有意义的话)。
如果您仍然想让所有类一次性导入,您可以使用
from submodule import Class
语法将它们全部导入到__init__.py
文件本身中,然后只需导入包含模块 -import mainmodule
并引用mainmodule.Class1
等,甚至使用from mainmodule import Class1, Class2, Class3
导入类直接添加到您的命名空间中并直接引用它们。In response to your comment to Adam's answer, regarding having 10 imports for 10 classes, firstly don't forget that there's no need to have one class per module in Python. Modules should be organised by functionality, so you can group related classes in a single file if that makes sense.
If you still wanted to make all the classes importable in one go, you could import them all in the
__init__.py
file itself using thefrom submodule import Class
syntax, then just import the containing module -import mainmodule
and refer tomainmodule.Class1
etc, or even usefrom mainmodule import Class1, Class2, Class3
to import the classes directly into your namespace and refer to them directly.Adam Bernier 对包的工作原理提供了很好的技术描述。 http://jcalderone.livejournal.com/ 中详细描述了如何安排和交付项目39794.html
Adam Bernier provides a good technical description of how packages work. A great description of how to arrange and ship a project is described in http://jcalderone.livejournal.com/39794.html