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

How do I use global variables in python functions?

本问题已经有最佳答案,请猛点这里访问。

如何在 python 函数中设置全局变量?


要在函数内部使用global变量,你需要在函数内部使用global <varName>,像这样。

testVar = 0



def testFunc():

  global testVar

  testVar += 1



print testVar

testFunc()

print testVar
>>> 

0

1

def testFunc2():

  print testVartestVar = []

def testFunc1():

  testVar = [2] # Will create a local testVar and assign it [2], but will not change the global variable.



def testFunc2():

  global testVar

  testVar = [2] # Will change the global variable.



def testFunc3():

  testVar.append(2) # Will change the global variable.
count = 0



def funct():

  global count

  count += 1

  return count



print funct() # prints 1

a = funct() # a = 2

print funct() # prints 3

print a # prints 2



print count # prints 3

def initCounter():

  count = 0

  def incrementCounter():

    count += 1

    return count



  #notice how you're returning the function with no parentheses 

  #so you return a function instead of a value

  return incrementCounter 



myFunct = initCounter()

print myFunct() # prints 1

a = myFunct() # a = 2

print myFunct() # prints 3

print a # prints 2



print count # raises an error! 

      # So you can use count for something else if needed!
a = 1



def f():

  # uses global because it hasn't been rebound

  print 'f: ',a



def g():

  # variable is rebound so global a isn't touched

  a = 2

  print 'g: ',a



def h():

  # specify that the a we want is the global variable

  global a

  a = 3

  print 'h: ',a



print 'global: ',a

f()

print 'global: ',a

g()

print 'global: ',a

h()

print 'global: ',a
global: 1

f: 1

global: 1

g: 2

global: 1

h: 3

global: 3

>>> c = 1

>>> def foo():

...   c = 0

...   c += 1

...   print c

...

>>> def bar():

...   global c

...   c += 1

...   print c

...

>>> foo()

1

>>> foo()

1

>>> foo()

1

>>> bar()

2

>>> bar()

3

#function

def test_f(x):

  y = x + 2

  return y



#execute function, and assign result as another variable

var = test_f(3)

#can use the output of test_f()!

print var   #returns 5

print var + 3 #returns 8

给出输出

testVar = 0



def testFunc():

  global testVar

  testVar += 1



print testVar

testFunc()

print testVar
>>> 

0

1

def testFunc2():

  print testVartestVar = []

def testFunc1():

  testVar = [2] # Will create a local testVar and assign it [2], but will not change the global variable.



def testFunc2():

  global testVar

  testVar = [2] # Will change the global variable.



def testFunc3():

  testVar.append(2) # Will change the global variable.
count = 0



def funct():

  global count

  count += 1

  return count



print funct() # prints 1

a = funct() # a = 2

print funct() # prints 3

print a # prints 2



print count # prints 3

def initCounter():

  count = 0

  def incrementCounter():

    count += 1

    return count



  #notice how you're returning the function with no parentheses 

  #so you return a function instead of a value

  return incrementCounter 



myFunct = initCounter()

print myFunct() # prints 1

a = myFunct() # a = 2

print myFunct() # prints 3

print a # prints 2



print count # raises an error! 

      # So you can use count for something else if needed!
a = 1



def f():

  # uses global because it hasn't been rebound

  print 'f: ',a



def g():

  # variable is rebound so global a isn't touched

  a = 2

  print 'g: ',a



def h():

  # specify that the a we want is the global variable

  global a

  a = 3

  print 'h: ',a



print 'global: ',a

f()

print 'global: ',a

g()

print 'global: ',a

h()

print 'global: ',a
global: 1

f: 1

global: 1

g: 2

global: 1

h: 3

global: 3

>>> c = 1

>>> def foo():

...   c = 0

...   c += 1

...   print c

...

>>> def bar():

...   global c

...   c += 1

...   print c

...

>>> foo()

1

>>> foo()

1

>>> foo()

1

>>> bar()

2

>>> bar()

3

#function

def test_f(x):

  y = x + 2

  return y



#execute function, and assign result as another variable

var = test_f(3)

#can use the output of test_f()!

print var   #returns 5

print var + 3 #returns 8

请记住,如果您想进行分配/更改它们,您只需要在函数内声明它们 global。打印和访问不需要 global

你可以的,

testVar = 0



def testFunc():

  global testVar

  testVar += 1



print testVar

testFunc()

print testVar
>>> 

0

1

def testFunc2():

  print testVartestVar = []

def testFunc1():

  testVar = [2] # Will create a local testVar and assign it [2], but will not change the global variable.



def testFunc2():

  global testVar

  testVar = [2] # Will change the global variable.



def testFunc3():

  testVar.append(2) # Will change the global variable.
count = 0



def funct():

  global count

  count += 1

  return count



print funct() # prints 1

a = funct() # a = 2

print funct() # prints 3

print a # prints 2



print count # prints 3

def initCounter():

  count = 0

  def incrementCounter():

    count += 1

    return count



  #notice how you're returning the function with no parentheses 

  #so you return a function instead of a value

  return incrementCounter 



myFunct = initCounter()

print myFunct() # prints 1

a = myFunct() # a = 2

print myFunct() # prints 3

print a # prints 2



print count # raises an error! 

      # So you can use count for something else if needed!
a = 1



def f():

  # uses global because it hasn't been rebound

  print 'f: ',a



def g():

  # variable is rebound so global a isn't touched

  a = 2

  print 'g: ',a



def h():

  # specify that the a we want is the global variable

  global a

  a = 3

  print 'h: ',a



print 'global: ',a

f()

print 'global: ',a

g()

print 'global: ',a

h()

print 'global: ',a
global: 1

f: 1

global: 1

g: 2

global: 1

h: 3

global: 3

>>> c = 1

>>> def foo():

...   c = 0

...   c += 1

...   print c

...

>>> def bar():

...   global c

...   c += 1

...   print c

...

>>> foo()

1

>>> foo()

1

>>> foo()

1

>>> bar()

2

>>> bar()

3

#function

def test_f(x):

  y = x + 2

  return y



#execute function, and assign result as another variable

var = test_f(3)

#can use the output of test_f()!

print var   #returns 5

print var + 3 #returns 8

没有像我们在第一个函数中那样声明它 global ,它仍然会给出正确的值。

list 为例,您不能在不声明 global 的情况下分配 list,但您可以调用它的方法并更改列表。如下。

testVar = 0



def testFunc():

  global testVar

  testVar += 1



print testVar

testFunc()

print testVar
>>> 

0

1

def testFunc2():

  print testVartestVar = []

def testFunc1():

  testVar = [2] # Will create a local testVar and assign it [2], but will not change the global variable.



def testFunc2():

  global testVar

  testVar = [2] # Will change the global variable.



def testFunc3():

  testVar.append(2) # Will change the global variable.
count = 0



def funct():

  global count

  count += 1

  return count



print funct() # prints 1

a = funct() # a = 2

print funct() # prints 3

print a # prints 2



print count # prints 3

def initCounter():

  count = 0

  def incrementCounter():

    count += 1

    return count



  #notice how you're returning the function with no parentheses 

  #so you return a function instead of a value

  return incrementCounter 



myFunct = initCounter()

print myFunct() # prints 1

a = myFunct() # a = 2

print myFunct() # prints 3

print a # prints 2



print count # raises an error! 

      # So you can use count for something else if needed!
a = 1



def f():

  # uses global because it hasn't been rebound

  print 'f: ',a



def g():

  # variable is rebound so global a isn't touched

  a = 2

  print 'g: ',a



def h():

  # specify that the a we want is the global variable

  global a

  a = 3

  print 'h: ',a



print 'global: ',a

f()

print 'global: ',a

g()

print 'global: ',a

h()

print 'global: ',a
global: 1

f: 1

global: 1

g: 2

global: 1

h: 3

global: 3

>>> c = 1

>>> def foo():

...   c = 0

...   c += 1

...   print c

...

>>> def bar():

...   global c

...   c += 1

...   print c

...

>>> foo()

1

>>> foo()

1

>>> foo()

1

>>> bar()

2

>>> bar()

3

#function

def test_f(x):

  y = x + 2

  return y



#execute function, and assign result as another variable

var = test_f(3)

#can use the output of test_f()!

print var   #returns 5

print var + 3 #returns 8

一个全局变量可以被任何函数访问,但是只有在函数内部使用'global'关键字显式声明它才能被修改。举个例子,一个实现计数器的函数。你可以用这样的全局变量来做到这一点:

testVar = 0



def testFunc():

  global testVar

  testVar += 1



print testVar

testFunc()

print testVar
>>> 

0

1

def testFunc2():

  print testVartestVar = []

def testFunc1():

  testVar = [2] # Will create a local testVar and assign it [2], but will not change the global variable.



def testFunc2():

  global testVar

  testVar = [2] # Will change the global variable.



def testFunc3():

  testVar.append(2) # Will change the global variable.
count = 0



def funct():

  global count

  count += 1

  return count



print funct() # prints 1

a = funct() # a = 2

print funct() # prints 3

print a # prints 2



print count # prints 3

def initCounter():

  count = 0

  def incrementCounter():

    count += 1

    return count



  #notice how you're returning the function with no parentheses 

  #so you return a function instead of a value

  return incrementCounter 



myFunct = initCounter()

print myFunct() # prints 1

a = myFunct() # a = 2

print myFunct() # prints 3

print a # prints 2



print count # raises an error! 

      # So you can use count for something else if needed!
a = 1



def f():

  # uses global because it hasn't been rebound

  print 'f: ',a



def g():

  # variable is rebound so global a isn't touched

  a = 2

  print 'g: ',a



def h():

  # specify that the a we want is the global variable

  global a

  a = 3

  print 'h: ',a



print 'global: ',a

f()

print 'global: ',a

g()

print 'global: ',a

h()

print 'global: ',a
global: 1

f: 1

global: 1

g: 2

global: 1

h: 3

global: 3

>>> c = 1

>>> def foo():

...   c = 0

...   c += 1

...   print c

...

>>> def bar():

...   global c

...   c += 1

...   print c

...

>>> foo()

1

>>> foo()

1

>>> foo()

1

>>> bar()

2

>>> bar()

3

#function

def test_f(x):

  y = x + 2

  return y



#execute function, and assign result as another variable

var = test_f(3)

#can use the output of test_f()!

print var   #returns 5

print var + 3 #returns 8

现在,这一切都很好,但通常将全局变量用于除常量之外的任何东西都不是一个好主意。你可以有一个使用闭包的替代实现,这将避免污染命名空间并且更干净:

testVar = 0



def testFunc():

  global testVar

  testVar += 1



print testVar

testFunc()

print testVar
>>> 

0

1

def testFunc2():

  print testVartestVar = []

def testFunc1():

  testVar = [2] # Will create a local testVar and assign it [2], but will not change the global variable.



def testFunc2():

  global testVar

  testVar = [2] # Will change the global variable.



def testFunc3():

  testVar.append(2) # Will change the global variable.
count = 0



def funct():

  global count

  count += 1

  return count



print funct() # prints 1

a = funct() # a = 2

print funct() # prints 3

print a # prints 2



print count # prints 3

def initCounter():

  count = 0

  def incrementCounter():

    count += 1

    return count



  #notice how you're returning the function with no parentheses 

  #so you return a function instead of a value

  return incrementCounter 



myFunct = initCounter()

print myFunct() # prints 1

a = myFunct() # a = 2

print myFunct() # prints 3

print a # prints 2



print count # raises an error! 

      # So you can use count for something else if needed!
a = 1



def f():

  # uses global because it hasn't been rebound

  print 'f: ',a



def g():

  # variable is rebound so global a isn't touched

  a = 2

  print 'g: ',a



def h():

  # specify that the a we want is the global variable

  global a

  a = 3

  print 'h: ',a



print 'global: ',a

f()

print 'global: ',a

g()

print 'global: ',a

h()

print 'global: ',a
global: 1

f: 1

global: 1

g: 2

global: 1

h: 3

global: 3

>>> c = 1

>>> def foo():

...   c = 0

...   c += 1

...   print c

...

>>> def bar():

...   global c

...   c += 1

...   print c

...

>>> foo()

1

>>> foo()

1

>>> foo()

1

>>> bar()

2

>>> bar()

3

#function

def test_f(x):

  y = x + 2

  return y



#execute function, and assign result as another variable

var = test_f(3)

#can use the output of test_f()!

print var   #returns 5

print var + 3 #returns 8

考虑以下代码:

testVar = 0



def testFunc():

  global testVar

  testVar += 1



print testVar

testFunc()

print testVar
>>> 

0

1

def testFunc2():

  print testVartestVar = []

def testFunc1():

  testVar = [2] # Will create a local testVar and assign it [2], but will not change the global variable.



def testFunc2():

  global testVar

  testVar = [2] # Will change the global variable.



def testFunc3():

  testVar.append(2) # Will change the global variable.
count = 0



def funct():

  global count

  count += 1

  return count



print funct() # prints 1

a = funct() # a = 2

print funct() # prints 3

print a # prints 2



print count # prints 3

def initCounter():

  count = 0

  def incrementCounter():

    count += 1

    return count



  #notice how you're returning the function with no parentheses 

  #so you return a function instead of a value

  return incrementCounter 



myFunct = initCounter()

print myFunct() # prints 1

a = myFunct() # a = 2

print myFunct() # prints 3

print a # prints 2



print count # raises an error! 

      # So you can use count for something else if needed!
a = 1



def f():

  # uses global because it hasn't been rebound

  print 'f: ',a



def g():

  # variable is rebound so global a isn't touched

  a = 2

  print 'g: ',a



def h():

  # specify that the a we want is the global variable

  global a

  a = 3

  print 'h: ',a



print 'global: ',a

f()

print 'global: ',a

g()

print 'global: ',a

h()

print 'global: ',a
global: 1

f: 1

global: 1

g: 2

global: 1

h: 3

global: 3

>>> c = 1

>>> def foo():

...   c = 0

...   c += 1

...   print c

...

>>> def bar():

...   global c

...   c += 1

...   print c

...

>>> foo()

1

>>> foo()

1

>>> foo()

1

>>> bar()

2

>>> bar()

3

#function

def test_f(x):

  y = x + 2

  return y



#execute function, and assign result as another variable

var = test_f(3)

#can use the output of test_f()!

print var   #returns 5

print var + 3 #returns 8

输出:

testVar = 0



def testFunc():

  global testVar

  testVar += 1



print testVar

testFunc()

print testVar
>>> 

0

1

def testFunc2():

  print testVartestVar = []

def testFunc1():

  testVar = [2] # Will create a local testVar and assign it [2], but will not change the global variable.



def testFunc2():

  global testVar

  testVar = [2] # Will change the global variable.



def testFunc3():

  testVar.append(2) # Will change the global variable.
count = 0



def funct():

  global count

  count += 1

  return count



print funct() # prints 1

a = funct() # a = 2

print funct() # prints 3

print a # prints 2



print count # prints 3

def initCounter():

  count = 0

  def incrementCounter():

    count += 1

    return count



  #notice how you're returning the function with no parentheses 

  #so you return a function instead of a value

  return incrementCounter 



myFunct = initCounter()

print myFunct() # prints 1

a = myFunct() # a = 2

print myFunct() # prints 3

print a # prints 2



print count # raises an error! 

      # So you can use count for something else if needed!
a = 1



def f():

  # uses global because it hasn't been rebound

  print 'f: ',a



def g():

  # variable is rebound so global a isn't touched

  a = 2

  print 'g: ',a



def h():

  # specify that the a we want is the global variable

  global a

  a = 3

  print 'h: ',a



print 'global: ',a

f()

print 'global: ',a

g()

print 'global: ',a

h()

print 'global: ',a
global: 1

f: 1

global: 1

g: 2

global: 1

h: 3

global: 3

>>> c = 1

>>> def foo():

...   c = 0

...   c += 1

...   print c

...

>>> def bar():

...   global c

...   c += 1

...   print c

...

>>> foo()

1

>>> foo()

1

>>> foo()

1

>>> bar()

2

>>> bar()

3

#function

def test_f(x):

  y = x + 2

  return y



#execute function, and assign result as another variable

var = test_f(3)

#can use the output of test_f()!

print var   #returns 5

print var + 3 #returns 8

基本上,当您需要每个函数访问同一个变量(对象)时,您会使用全局变量。不过,这并不总是最好的方法。


在下面的示例中,我们在任何其他函数之外定义了一个变量 c。在 foo 中,我们还声明了一个 c,将其递增并打印出来。您可以看到重复调用 foo() 将一遍又一遍地产生相同的结果,因为 foo 中的 c 在函数范围内是本地的。

然而,在bar 中,关键字global 被添加到c 之前。现在,变量 c 引用了在全局范围内定义的任何变量 c(即,我们在函数之前定义的 c = 1 实例)。调用 bar 重复更新全局 c 而不是本地范围的。

testVar = 0



def testFunc():

  global testVar

  testVar += 1



print testVar

testFunc()

print testVar
>>> 

0

1

def testFunc2():

  print testVartestVar = []

def testFunc1():

  testVar = [2] # Will create a local testVar and assign it [2], but will not change the global variable.



def testFunc2():

  global testVar

  testVar = [2] # Will change the global variable.



def testFunc3():

  testVar.append(2) # Will change the global variable.
count = 0



def funct():

  global count

  count += 1

  return count



print funct() # prints 1

a = funct() # a = 2

print funct() # prints 3

print a # prints 2



print count # prints 3

def initCounter():

  count = 0

  def incrementCounter():

    count += 1

    return count



  #notice how you're returning the function with no parentheses 

  #so you return a function instead of a value

  return incrementCounter 



myFunct = initCounter()

print myFunct() # prints 1

a = myFunct() # a = 2

print myFunct() # prints 3

print a # prints 2



print count # raises an error! 

      # So you can use count for something else if needed!
a = 1



def f():

  # uses global because it hasn't been rebound

  print 'f: ',a



def g():

  # variable is rebound so global a isn't touched

  a = 2

  print 'g: ',a



def h():

  # specify that the a we want is the global variable

  global a

  a = 3

  print 'h: ',a



print 'global: ',a

f()

print 'global: ',a

g()

print 'global: ',a

h()

print 'global: ',a
global: 1

f: 1

global: 1

g: 2

global: 1

h: 3

global: 3

>>> c = 1

>>> def foo():

...   c = 0

...   c += 1

...   print c

...

>>> def bar():

...   global c

...   c += 1

...   print c

...

>>> foo()

1

>>> foo()

1

>>> foo()

1

>>> bar()

2

>>> bar()

3

#function

def test_f(x):

  y = x + 2

  return y



#execute function, and assign result as another variable

var = test_f(3)

#can use the output of test_f()!

print var   #returns 5

print var + 3 #returns 8

在函数中使用 global <variable name> 显式声明应该会有所帮助


几天来我一直在努力解决同样的问题/误解了我想要的东西,我认为您可能想要完成的是让函数输出结果,可以在函数完成运行后使用。

您可以在上面完成的方法是使用返回"一些结果",然后将其分配给函数之后的变量。

下面是一个例子:

testVar = 0



def testFunc():

  global testVar

  testVar += 1



print testVar

testFunc()

print testVar
>>> 

0

1

def testFunc2():

  print testVartestVar = []

def testFunc1():

  testVar = [2] # Will create a local testVar and assign it [2], but will not change the global variable.



def testFunc2():

  global testVar

  testVar = [2] # Will change the global variable.



def testFunc3():

  testVar.append(2) # Will change the global variable.
count = 0



def funct():

  global count

  count += 1

  return count



print funct() # prints 1

a = funct() # a = 2

print funct() # prints 3

print a # prints 2



print count # prints 3

def initCounter():

  count = 0

  def incrementCounter():

    count += 1

    return count



  #notice how you're returning the function with no parentheses 

  #so you return a function instead of a value

  return incrementCounter 



myFunct = initCounter()

print myFunct() # prints 1

a = myFunct() # a = 2

print myFunct() # prints 3

print a # prints 2



print count # raises an error! 

      # So you can use count for something else if needed!
a = 1



def f():

  # uses global because it hasn't been rebound

  print 'f: ',a



def g():

  # variable is rebound so global a isn't touched

  a = 2

  print 'g: ',a



def h():

  # specify that the a we want is the global variable

  global a

  a = 3

  print 'h: ',a



print 'global: ',a

f()

print 'global: ',a

g()

print 'global: ',a

h()

print 'global: ',a
global: 1

f: 1

global: 1

g: 2

global: 1

h: 3

global: 3

>>> c = 1

>>> def foo():

...   c = 0

...   c += 1

...   print c

...

>>> def bar():

...   global c

...   c += 1

...   print c

...

>>> foo()

1

>>> foo()

1

>>> foo()

1

>>> bar()

2

>>> bar()

3

#function

def test_f(x):

  y = x + 2

  return y



#execute function, and assign result as another variable

var = test_f(3)

#can use the output of test_f()!

print var   #returns 5

print var + 3 #returns 8

普通变量只能在函数内部使用,全局变量可以在函数外部调用,但如果不需要,请不要使用它,它会产生错误,大型编程公司认为这是一个菜鸟要做的事情。


相关推荐

  • Spring部署设置openshift

    Springdeploymentsettingsopenshift我有一个问题让我抓狂了三天。我根据OpenShift帐户上的教程部署了spring-eap6-quickstart代码。我已配置调试选项,并且已将Eclipse工作区与OpehShift服务器同步-服务器上的一切工作正常,但在Eclipse中出现无法消除的错误。我有这个错误:cvc-complex-type.2.4.a:Invali…
    2025-04-161
  • 检查Java中正则表达式中模式的第n次出现

    CheckfornthoccurrenceofpatterninregularexpressioninJava本问题已经有最佳答案,请猛点这里访问。我想使用Java正则表达式检查输入字符串中特定模式的第n次出现。你能建议怎么做吗?这应该可以工作:MatchResultfindNthOccurance(intn,Patternp,CharSequencesrc){Matcherm=p.matcher…
    2025-04-161
  • 如何让 JTable 停留在已编辑的单元格上

    HowtohaveJTablestayingontheeditedcell如果有人编辑JTable的单元格内容并按Enter,则内容会被修改并且表格选择会移动到下一行。是否可以禁止JTable在单元格编辑后转到下一行?原因是我的程序使用ListSelectionListener在单元格选择上同步了其他一些小部件,并且我不想在编辑当前单元格后选择下一行。Enter的默认绑定是名为selectNext…
    2025-04-161
  • Weblogic 12c 部署

    Weblogic12cdeploy我正在尝试将我的应用程序从Tomcat迁移到Weblogic12.2.1.3.0。我能够毫无错误地部署应用程序,但我遇到了与持久性提供程序相关的运行时错误。这是堆栈跟踪:javax.validation.ValidationException:CalltoTraversableResolver.isReachable()threwanexceptionatorg.…
    2025-04-161
  • Resteasy Content-Type 默认值

    ResteasyContent-Typedefaults我正在使用Resteasy编写一个可以返回JSON和XML的应用程序,但可以选择默认为XML。这是我的方法:@GET@Path("/content")@Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})publicStringcontentListRequestXm…
    2025-04-161
  • 代码不会停止运行,在 Java 中

    thecodedoesn'tstoprunning,inJava我正在用Java解决项目Euler中的问题10,即"Thesumoftheprimesbelow10is2+3+5+7=17.Findthesumofalltheprimesbelowtwomillion."我的代码是packageprojecteuler_1;importjava.math.BigInteger;importjava…
    2025-04-161
  • Out of memory java heap space

    Outofmemoryjavaheapspace我正在尝试将大量文件从服务器发送到多个客户端。当我尝试发送大小为700mb的文件时,它显示了"OutOfMemoryjavaheapspace"错误。我正在使用Netbeans7.1.2版本。我还在属性中尝试了VMoption。但仍然发生同样的错误。我认为阅读整个文件存在一些问题。下面的代码最多可用于300mb。请给我一些建议。提前致谢publicc…
    2025-04-161
  • Log4j 记录到共享日志文件

    Log4jLoggingtoaSharedLogFile有没有办法将log4j日志记录事件写入也被其他应用程序写入的日志文件。其他应用程序可以是非Java应用程序。有什么缺点?锁定问题?格式化?Log4j有一个SocketAppender,它将向服务发送事件,您可以自己实现或使用与Log4j捆绑的简单实现。它还支持syslogd和Windows事件日志,这对于尝试将日志输出与来自非Java应用程序…
    2025-04-161