Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:将变量添加到导入函数的作用域中_Python_Scope - Fatal编程技术网

Python:将变量添加到导入函数的作用域中

Python:将变量添加到导入函数的作用域中,python,scope,Python,Scope,考虑以下情况: #module.py def test(): foo = bar+'foo' print foo if __name__ == '__main__': bar='test' test() 主文件是: #main.py import module bar = 'test' module.test() 运行main.py显然会生成namererror。我知道有几种方法可以解决这一问题(例如,在main.py中重新定义函数),但我的问题是:如何在不修

考虑以下情况:

#module.py
def test():
    foo = bar+'foo'
    print foo
if __name__ == '__main__':
    bar='test'
    test()
主文件是:

#main.py
import module
bar = 'test'
module.test()
运行main.py显然会生成
namererror
。我知道有几种方法可以解决这一问题(例如,在main.py中重新定义函数),但我的问题是:如何在不修改module.py代码的情况下将bar变量添加到函数范围,以及更一般地说,在这种情况下,什么是最佳做法

编辑: 使用模块导入中的
*
,同样的问题如何