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

时间:2016-11-03 09:57:00

标签: python python-2.7

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

例如,此代码抛出错误:

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

由于a_variable fun2有效,fun1怎么回事?我该如何解决这个问题?我不想将其他参数添加到fun1

1 个答案:

答案 0 :(得分:1)

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

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

如果您没有更改参数列表,则会收到另一个错误:'a_variable' is local and global

相关问题