python - 如何从 import * 导入类,而不是模块
问题描述
我有一个文件夹结构如下
\root
|-collections
|-__init__.py
|-collection1.py => contains Collection1 class
|-collection2.py => contains Collection2 class
|-...so on
|-db.py
在 db.py 中,我需要使用所有的 Collection<n> 类。有没有办法像下面的代码一样导入它们?显然 __init__.py 中的 __all__ 变量只允许模块名称,而不是类。
# db.py
from root.collections import *
a = Collection1()
b = Collection2()
...
这是我的试验和错误
# collections\__init__.py
from collection1 import Collection1
from collection2 import Collection2
from collection3 import Collection3
__all__ = ['Collection1', 'Collection2', 'Collection3']
# db.py
def test_collections():
from root.collections import *
a = Collection1()
test_collections()
这给了我...
SyntaxError: import * only allowed at module level
解决方案
导入类__init__.py
:
__all__ = ['Collection1', 'Collection2']
from .collection1 import Collection1
from .collection2 import Collection2
推荐阅读
- networking - 为什么公共 IPv4 地址范围不同于私有 IPv4 地址
- javascript - onclick返回php文件后自动发送html表单
- python - 在 django admin 中保存内联配置文件表单时出错
- java - 如何检查字符串的一部分是否为小写?
- css - 根据屏幕尺寸更改幻灯片图像选择 - Shopify
- google-cloud-platform - Google Cloud 使用 PKCE 运行 OAuth2 身份验证
- c++ - c++ 使用 reinterpret_cast 转换 unique_ptr
* to unique_ptr * 用于创建可转换的树结构 - python-3.x - 如何在 djnago api 中允许方法 POST
- java - 当我尝试使用着色器 (Java) 时,OpenGL 向我发送堆栈下溢错误
- android - 如何创建android布局按钮结束,并从中心的textview开始