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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16865213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:51:39  来源:igfitidea点击:

How do I use global variables in python functions?

pythonglobal-variables

提问by stgeorge

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

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

采纳答案by Sukrit Kalra

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

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

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 globalinside the function if you want to do assignments / change them. globalis not needed for printing and accessing.

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

You can do,

你可以做,

def testFunc2():
    print testVar

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

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

Using a listas an example, you cannot assign a listwithout declaring it globalbut you can call it's methods and change the list. Like follows.

以 alist为例,您不能在list不声明的情况下分配 a ,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.

回答by vladfau

Explicit declaration by using global <variable name>inside a function should help

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

回答by sberry

In the example below we have a variable cdefined outside of any other function. In foowe also declare a c, increment it, and print it out. You can see that repeatedly calling foo()will yield the same result over and over again, because the cin foois local in scope to the function.

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

In bar, however, the keyword globalis added before c. Now the variable creferences any variable cdefined in the global scope (ie. our c = 1instance defined before the functions). Calling barrepeatedly updates the global cinstead of one scoped locally.

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

回答by korylprince

Consider the following code:

考虑以下代码:

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

Output:

输出:

global:  1
f:  1
global:  1
g:  2
global:  1
h:  3
global:  3

Basically you use a global variable when you need every function to access the same variable (object). This isn't always the best way though.

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

回答by James

A global can be accessed by any function, but it can only be modified if you explicitly declare it with the 'global' keyword inside the function. Take, for example, a function that implements a counter. You could do it with global variables like this:

任何函数都可以访问全局变量,但只有在函数内部使用 '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

Now, this is all fine and good, but it is generally not a good idea to use global variables for anything except constants. You could have an alternate implementation using closures, which would avoid polluting the namespace and be much cleaner:

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

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!

回答by Fox

A normal variable is only usable inside of a function, a global variable can be called for outside the function, but don't use this if you don't need to, it can create errors and big programming companies consider this a rookie thing to do.

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

回答by FlyingZebra1

I've grappled with the same question / misunderstood what I wanted for a few days, and I think what you may be trying to accomplish is have a function output a result, that can be used after the function finishes running.

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

The way you can accomplish above is by using return"some result", and then assigning that to a variable after a function. Here's an example below:

您可以在上面完成的方法是使用return“some result”,然后将其分配给函数后的变量。下面是一个例子:

#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