首页 > 解决方案 > 如何从 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

标签: python

解决方案


导入类__init__.py

__all__ = ['Collection1', 'Collection2']

from .collection1 import Collection1
from .collection2 import Collection2

推荐阅读