我有两个文件 module.py
和 main.py
在module.py
中,我有一个函数,它使用在其范围之外定义的常量。
#module.py
def add(x):
s = x + const
return s
if __name__ == '__main__':
const = 2
print(add(2))
直接运行时,它会打印 4
作为输出。
在main.py
中我有:
#main.py
import module as m
const = 2
print(m.add(2))
它给出错误:NameError:名称'const'未定义
有没有办法让 m.add() 在 main.py
全局范围内查找 const
?我不想将 const 作为函数变量传递给 add() 。
最佳答案
尚不清楚您的实际用例是什么,但如果您想在模块之间共享变量,则需要在模块范围内定义该变量。
在一个模块中声明它:
#module.py
const = 0 # declare as global of module.py
def add(x):
s = x + const
return s
if __name__ == '__main__':
const = 3
print(add(2))
...并在另一个中引用它:
#main.py
import module as m
m.const = 3 # reference module's variable
print(m.add(2))
关于python:导入引用全局范围的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35065249/