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

时间:2013-05-31 20:12:59

标签: python global-variables

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

7 个答案:

答案 0 :(得分:23)

要在函数中使用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,它仍然会给出正确的值。

使用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.

答案 1 :(得分:2)

请考虑以下代码:

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

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

答案 2 :(得分:2)

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

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!

答案 3 :(得分:1)

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

答案 4 :(得分:1)

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

但是,在bar中,关键字global会在c之前添加。现在,变量c引用全局范围中定义的任何变量c(即在函数之前定义的c = 1实例)。调用bar会反复更新全局c,而不是在本地更新一个范围。

>>> 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

答案 5 :(得分:0)

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

答案 6 :(得分:0)

我已经解决了同样的问题/误解了我想要的几天,我认为你可能想要完成的是一个函数输出结果,可以在函数完成运行后使用

上面的方法是使用返回&#34;某些结果&#34;,然后在函数后将其分配给变量。 以下是一个例子:

#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