python - 从在 python 中导入我的函数的文件中获取变量

标签 python python-3.x operating-system

我有 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/

相关文章:

python - Pandas 在列中查找序列或模式

python - 将两个 numpy 掩码数组加在一起

python-3.x - Python 无法访问我的 USB 设备 - 权限不足

python - 为什么 Python 2.7 中的 print 括号是自愿的?

memory - 如何实现/设置数据断点?

linux - 如何设置 headless firefox 浏览器 Ubuntu 服务器

python - 无法在 MatPlotLib 3d 上使 Axis 右对齐

python - 如何在 .fit() 方法中对多个标签(trainy)使用一种热编码?

python - 如何打印列表的某些部分?

Python 使用 pexpect 通过 scp 发送文件