gpt4 book ai didi

python - 在 Python 中使用字符串导入

转载 作者:行者123 更新时间:2023-11-28 22:04:02 24 4
gpt4 key购买 nike

简短版:

假设我有一个字符串 str 和一个文件 functions.py,我想从中导入一个名称存储在 str 中的方法>。

我该怎么做?我想要这样的东西:

from functions.py import str

但是对 str 进行了评估,而不是导入方法“str”(不存在)。

经过一些谷歌搜索后,我接近(我希望):

func_name = str
_tmp = __import__('functions.py', globals(), locals(), ['func_name'], -1)
func = ???? <what to put here?>

提前致谢。

编辑:TMI。

最佳答案

假设您将模块导入 _tmp 的代码有效,那么最后一步很简单:

func = getattr(_tmp, func_name)

关于python - 在 Python 中使用字符串导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7785726/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com