Python 如何在函数中引用全局变量?

Python 如何在函数中引用全局变量?,python,python-2.7,Python,Python 2.7,我想通过代码使用一些变量,当然,如果变量是全局变量,就可以了。但是我想使用函数,所以我可以在将来的工作中传递一些参数 例如,此代码引发了一个错误: def fun1(): print a_variable def fun2(a_variable='hello, world'): fun1() fun2('hello, world') 错误: -----------------------------------------------------------------------

我想通过代码使用一些变量,当然,如果变量是全局变量,就可以了。但是我想使用函数,所以我可以在将来的工作中传递一些参数

例如,此代码引发了一个错误:

def fun1():
  print a_variable

def fun2(a_variable='hello, world'):
  fun1()

fun2('hello, world')
错误:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-42-31e8e239671e> in <module>()
      5   fun1()
      6 
----> 7 fun2('hello, world')

<ipython-input-42-31e8e239671e> in fun2(a_variable)
      3 
      4 def fun2(a_variable='hello, world'):
----> 5   fun1()
      6 
      7 fun2('hello, world')

<ipython-input-42-31e8e239671e> in fun1()
      1 def fun1():
----> 2   print a_variable
      3 
      4 def fun2(a_variable='hello, world'):
      5   fun1()

NameError: global name 'a_variable' is not defined
---------------------------------------------------------------------------
NameError回溯(最近一次呼叫上次)
在()
5 fun1()
6.
---->7 fun2(“你好,世界”)
在fun2中(a_变量)
3.
4 def fun2(一个_变量='hello,world'):
---->5 fun1()
6.
7 fun2(“你好,世界”)
在fun1()中
1 def fun1():
---->2打印一个_变量
3.
4 def fun2(一个_变量='hello,world'):
5 fun1()
NameError:未定义全局名称“a_变量”

既然
u变量
fun2
中有效,为什么
fun1
不有效?我如何解决这个问题?我不想给
fun1

添加额外的参数。在python中,有一个简单的语句可以使变量成为全局变量。但是,首先需要更改
fun2()
参数列表中变量的名称。此更改后,您可以插入
全局
-语句:

def fun2(a='hello, world'):
    global a_variable # declaration
    a_variable = a # definition
    fun1()

如果不更改参数列表,则会出现另一个错误:
'a_variable'是本地和全局的

您好,谢谢。这很有效。但我真的不喜欢这样。因为这会带来一个全局变量,但实际上“a_variable”只需要在“fun2”的名称空间中是“global”。也许您应该将行
global a_variable
放在任何函数之外(但仍然在第一次函数调用之前)。然后您不需要调用
fun2
使变量成为全局变量。好的,
global a_variable
在函数外部不会执行任何操作。它可能不起作用,因为在
fun2
-函数中,变量被解释为本地变量,只要您不明确地告诉解释器将其引用到全局变量。换句话说:您可能需要
fun2()
中的
global a_变量
语句