只导入模块的某些部分,但将这些部分列为字符串

2024-04-24 09:20:16 发布

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

这个问题被标记为duplicate。然而,duplicate问题涉及模块,而我的问题是如何导入模块的部分。你知道吗

我知道我可以通过使用from mymodule import myfunctionimport模块的某些部分。如果我想导入一些东西,但我需要将它们列为字符串,该怎么办。例如:

import_things = ['thing1', 'thing2', 'thing2']
from mymodule import import_things

我确实问过this question,但是看起来我也需要对我的代码使用上面的技巧(如果有的话)。你知道吗

感谢您的帮助。你知道吗


Tags: 模块字符串代码from标记import技巧this
1条回答
网友
1楼 · 发布于 2024-04-24 09:20:16
import importlib

base_module = importlib.import_module('mymodule')
imported_things = {thing: getattr(base_module, thing) for thing in import_things}

imported_things['thing1']() # Function call

如果您希望能够使用已全局导入的内容,请执行以下操作:

globals().update(imported_things)
thing1() # function call

要删除导入,可以执行以下操作

del thing1

或者

del globals()['thing1']

另一个有用的操作是^{}一个模块

相关问题 更多 >