Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.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 - Fatal编程技术网

Python 未定义全局名称,应如何导入?

Python 未定义全局名称,应如何导入?,python,Python,我遇到了这个错误,全局名称**在我的代码中没有定义,下面是一个简单的例子 test1.py def f(): print 'inside f()' g() return test2.py def g(): print 'inside g()' from test1 import f f() 在终端中运行python test2.py时,出现错误name错误:未定义全局名称“g”,如何导入test1以避免此错误?如果不想将对f()的调用分离到其他文件,则可以执

我遇到了这个错误,
全局名称**在我的代码中没有定义
,下面是一个简单的例子

test1.py

 def f():
   print 'inside f()'
   g()
   return
test2.py

 def g():
   print 'inside g()'

 from test1 import f
 f()

在终端中运行
python test2.py
时,出现错误
name错误:未定义全局名称“g”
,如何导入
test1
以避免此错误?

如果不想将对
f()
的调用分离到其他文件,则可以执行以下操作:

test1.py

 def f():
   print 'inside f()'
   g()
   return
从test2导入g
def():
打印“内部f()”
g()
返回
test2.py

 def g():
   print 'inside g()'

 from test1 import f
 f()
def g():
打印“内g()
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
从test1导入f
f()
这样,test2中对
f()
的调用只有在脚本执行时才会运行:

$ python test2.py
inside f()
inside g()

如果您在
test1
中使用
g
,您需要在
test1
中导入
g
@BrenBarn,如果我在
test1
中导入
g
,然后在
test2
中导入
f
,这将导致循环导入,这会是一个问题吗?如果您有循环导入,Python将做正确的事情,但相互进口是一种不良思想的代码气味。如果有一个依赖项,正如您所示,它们属于同一个模块/命名空间。