To use global
函数内的变量,你需要做global <varName>
在函数内部,就像这样。
testVar = 0
def testFunc():
global testVar
testVar += 1
print testVar
testFunc()
print testVar
给出输出
>>>
0
1
请记住,您只需要声明它们global
如果您想进行分配/更改它们,请在函数内部进行。global
不需要打印和访问。
你可以做,
def testFunc2():
print testVar
没有声明它global
正如我们在第一个函数中所做的那样,它仍然会给出正确的值。
Using a list
例如,您不能分配list
没有声明它global
但您可以调用它的方法并更改列表。就像下面这样。
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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)