我如何在Python函数中使用全局变量? [英] How do I use global variables in python functions?

查看:581
本文介绍了我如何在Python函数中使用全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案使用 global 函数内的变量,您需要在函数内部执行 global< varName> ,就像这样。

  testVar = 0 

def testFunc():
全局testVar
testVar + = 1

print testVar
testFunc()
print testVar

给出输出

 >>> 
0
1

请记住,您只需要声明它们全局在函数内部,如果你想做赋值/改变它们。 全球不需要打印和存取。



您可以这样做,

  def testFunc2():
print testVar

没有像第一个函数那样声明它< global ,它仍然会给出值。



列表为例,您不能指定 list 没有声明它全局,但你可以调用它的方法并改变列表。如下。

  testVar = [] 
def testFunc1():
testVar = [2]#将创建一个本地testVar并将其分配[2],但不会更改全局变量。

def testFunc2():
全局testVar
testVar = [2]#将改变全局变量。

def testFunc3():
testVar.append(2)#将改变全局变量。


How do I set a global variable inside of a python function?

解决方案

To use global variables inside a function, you need to do global <varName> inside the function, like so.

testVar = 0

def testFunc():
    global testVar
    testVar += 1

print testVar
testFunc()
print testVar

gives the output

>>> 
0
1

Keep in mind, that you only need to declare them global inside the function if you want to do assignments / change them. global is not needed for printing and accessing.

You can do,

def testFunc2():
    print testVar

without declaring it global as we did in the first function and it'll still give the value all right.

Using a list as an example, you cannot assign a list without declaring it global but you can call it's methods and change the list. Like follows.

testVar = []
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.

这篇关于我如何在Python函数中使用全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆