我有 2 个文件:
Main.py
from test import test
def main():
sol = 'hello'
if test() == sol:
print('Yes')
else:
print('No')
test.py
def test():
return 'hello'
有没有办法在我的测试函数中访问另一个文件中的 sol 变量?我想做这样的事情:
def test():
return sol
这样它总是与 Main.py 中的变量相同。我尝试了 Python extract variables from an imported file 中提到的解决方案但它对我不起作用。感谢您的帮助
编辑:我想在不更改 Main.py 文件的情况下执行此操作
最佳答案
由于 sol
未在函数中定义,因此您需要将其声明为全局函数,以便在函数中使用它。将 test.py
更改为以下...
test():
global sol
return sol
希望对您有所帮助。
关于python - 从在 python 中导入我的函数的文件中获取变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52564716/