如何从import*而不是模块导入类

2024-09-27 21:31:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件夹结构如下

\root
   |-collections
     |-__init__.py
     |-collection1.py   => contains Collection1 class
     |-collection2.py   => contains Collection2 class
     |-...so on
   |-db.py

在db.py内部,我需要使用所有集合<;n>;上课。有没有办法像下面的代码一样导入它们?显然,init.py中的变量只允许模块名,而不允许类

# 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

Tags: frompytestimportdbinitrootcollections
1条回答
网友
1楼 · 发布于 2024-09-27 21:31:56

导入__init__.py中的类:

__all__ = ['Collection1', 'Collection2']

from .collection1 import Collection1
from .collection2 import Collection2

相关问题 更多 >

    热门问题