在您声明为重复之前
我查看了以下内容:
python function call with variable
Calling a function of a module from a string with the function's name
Executing a function by variable name in Python
https://ubuntuforums.org/showthread.php?t=1110989
等等,但没有运气。
我正在开发一款游戏。现在我正在处理 SAVE / LOAD 功能,但我无处可去。
我想从另一个 py 或 txt 文件中获取一段文字,然后读取我的主要 py 文件,然后调用功能取决于第二个文件中的文本字符串。
SCRIPT1:
#imports
from script2 import SaveCode
#Code
def Test():
print('Hello, World!')
callable(SaveCode)
SCRIPT2:
SaveCode = Test()
这不会奏效。有人可以帮助我吗?
答案 0 :(得分:1)
除非您使用eval
或exec
使用isn't recommended评估该字符串,否则此功能无效。
从我收集的内容中,你在script2中有一个字符串,并希望在script1中根据该字符串执行一个函数。你可以做的是定义一个字典,其中包含你映射到你想要调用的函数的字符串:
在 script1 :
中#imports
from script2 import SaveCode
#Code
def Test():
print('Hello, World!')
functions = {
'Test': Test
}
# Assuming that SaveCode = 'Test' in your second script,
# look up the corresponding function
function_to_run = functions[SaveCode]
# and call it
function_to_run() # prints Hello, World!
在 script2 :
SaveCode = 'Test'