Python,从模块导入函数
发布时间:2020-12-20 13:42:08 所属栏目:Python 来源:网络整理
导读:我有很多模块(数百个).在每个模块中,我至少有一个功能.我的问题是如何只用一行从所有模块导入所有功能?因为我不想这样做: from tests.test_001 import test_001_funcfrom tests.test_002 import test_002_funcfrom tests.test_003 import test_003_func...
我有很多模块(数百个).在每个模块中,我至少有一个功能.我的问题是如何只用一行从所有模块导入所有功能?因为我不想这样做:
from tests.test_001 import test_001_func from tests.test_002 import test_002_func from tests.test_003 import test_003_func ... from tests.test_999 import test_999_func test_xxx是模块,这些模块包含test_xxx_func函数,所有模块都在一个文件夹中. 我想用这样的东西: from tests import * test_001.test_001_func() 但这不起作用 解决方法
在tests目录中创建一个__init__.py文件并在其中放置:
__all__ = [ "test_001_func","test_002_func",# etc ] 然后你可以: import tests tests.test_001_func() 要么 from tests import * # Not the best way to do things. 注:导入*不是首选解决方案的原因是您从调用中删除了命名空间,因此您可以a)可能与其他模块中的名称发生冲突,并且b)您的代码不太清楚. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |