Bootstrap

Python基础入门----全局,局部和非局部变量

Python Global, Local and Nonlocal variables

In this article, you’ll learn about Python Global Variable, Local Variable, Nonlocal Variable and where to use them.

 

Table of Contents

Python全局,局部,非局部变量

在这篇文章了,你将学习到Python全局变量,局部变量,非局部变量和在哪儿使用他们。

 

表格内容

  • 全局变量
  • 局部变量
  • 全局和局部变量一起使用
  • 非局部变量

Global Variables

In Python, a variable declared outside of the function or in global scope is known as global variable. This means, global variable can be accessed inside or outside of the function.

Let's see an example on how a global variable is created in Python.

全局变量

在Python里,一个变量声明在函数外面或在全局变量范围都被认为是全局变量。这意思是,Python里全局变量被允许出现在函数里面或外面。


Example 1: Create a Global Variable

x = "global"

def foo():
    print("x inside :", x)

foo()
print("x outside:", x)

 

When we run the code, the will output be:

x inside : global
x outside: global

In above code, we created x as a global variable and defined a foo() to print the global variable x. Finally, we call the foo() which will print the value of x.

例子1:创建一个全局变量

运行结果为:

In [1]: x = "global"

In [2]: def foo():
   ...:     print("x inside :", x)
   ...:     

In [3]: foo()
x inside : global

In [4]: print("x outside:",x)
x outside: global

在上面代码中,我们创建x作为一个全局变量,定义一个foo()去打印一个全局变量x。最后,最后我们可以调用foo() 去打印x的值。


What if you want to change value of x inside a function?

x = "global"

def foo():
    x = x * 2
    print(x)
foo()

 

When we run the code, the will output be:

UnboundLocalError: local variable 'x' referenced before assignment

The output shows an error because Python treats x as a local variable and x is also not defined inside foo().

To make this work we use global keyword, to learn more visit Python Global Keyword.


如果你想改变在一个函数x的值?

执行代码将会报错,输出为:
 

In [5]: x = "global"

In [6]: def foo():
   ...:     x = x * 2
   ...:     print(x)
   ...:     

In [7]: foo()
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-7-624891b0d01a> in <module>()
----> 1 foo()

<ipython-input-6-960900f57950> in foo()
      1 def foo():
----> 2     x = x * 2
      3     print(x)
      4 

UnboundLocalError: local variable 'x' referenced before assignment

这输出展示的错误,因为Python认为x是局部变量,x也没有定义在foo()里面。

为了使它能工作,外面使用global关键字,让我们学习更多并参考Python全局关键字。

 


Local Variables

A variable declared inside the function's body or in the local scope is known as local variable.

Example 2: Accessing local variable outside the scope

def foo():
    y = "local"

foo()
print(y)

 

When we run the code, the will output be:

NameError: name 'y' is not defined

The output shows an error, because we are trying to access a local variable y in a global scope whereas the local variable only works inside foo() or local scope.

 

全局变量

一个变量声明在函数体里面或局部范围里面,被认为是局部变量。


例子2:访问局部变量外面的范围。

当外面执行代码是,我们将得到输出结果:

In [8]: def foo():
   ...:     y = "local"
   ...:     

In [9]: foo()

In [10]: print(y)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-10-36b2093251cd> in <module>()
----> 1 print(y)

NameError: name 'y' is not defined

这输出结果展示的错误,因为我们在尝试访问一个在全局范围的局部变量y, 然而局部变量仅仅工作在foo()里面或局部范围。

 


Let's see an example on how a local variable is created in Python.

Example 3: Create a Local Variable

Normally, we declare a variable inside the function to create a local variable.

def foo():
    y = "local"
    print(y)

foo()

 

When we run the code, it will output:

local

Let's take a look to the earlier problem where x was a global variable and we wanted to modify x inside foo().

 让我们看下一个例子,在Python如何创建局部变量。

例子3:创建一个局部变量

一般的,我们声明一个变量,在函数里面创建局部变量。

当我们执行代码是,它将输出:

In [11]: def foo():
   ....:     y = "local"
   ....:     print(y)
   ....:     

In [12]: foo
local

让我们看最早的问题,x是一个全局变量,我们在foo()里面改变x。


Global and local variables

Here, we will show how to use global variables and local variables in the same code.

Example 4: Using Global and Local variables in same code

x = "global"

def foo():
    global x
    y = "local"
    x = x * 2
    print(x)
    print(y)
    
foo()

 

When we run the code, the will output be:

global global 
local

全局和局部变量

这里,我们将展示怎样使用全局变量和局部变量在相同的代码。

例子4:使用全局和局部变量在相同的代码

 当我们运行代码,将会输出结果:

In [16]: x = "global"

In [17]: def foo():
   ....:     global x
   ....:     y = "local"
   ....:     x = x * 2
   ....:     print(x)
   ....:     print(y)
   ....:     

In [18]: foo()
globalglobal
local

In the above code, we declare x as a global and y as a local variable in the foo(). Then, we use multiplication operator * to modify the global variable x and we print both x and y.

After calling the foo(), the value of x becomes global global because we used the x * 2 to print two times global. After that, we print the value of local variable y i.e local.

在上面这段代码,我们声明x作为一个全局变量,y作为一个局部变量在foo()里。然后,我们使用乘法操作符*去改变这全局变量x,我们打印x和y两个数。


Example 5: Global variable and Local variable with same name

x = 5

def foo():
    x = 10
    print("local x:", x)

foo()
print("global x:", x)

 

When we run the code, the will output be:

local x: 10
global x: 5

例子5:全局变量和局部变量同名

当我们运行代码,我们就会输出结果:

In [19]: x = 5

In [20]: def foo():
   ....:     x = 10
   ....:     print("local x:",x)
   ....:     

In [21]: foo()
local x: 10

In [22]: print("global x:",x)
global x: 5

 


In above code, we used same name x for both global variable and local variable. We get different result when we print same variable because the variable is declared in both scopes, i.e. the local scope inside foo() and global scope outside foo().

When we print the variable inside the foo() it outputs local x: 10, this is called local scope of variable.

Similarly, when we print the variable outside the foo(), it outputs global x: 5, this is called global scope of variable.

以上代码,对于全局变量和局部变量我们使用相同的名字x 。我们得到不同的结果当我们打印相同的变量时,因为变量时声明在两个范围,例如:局部范围在foo()里面,全局范围在foo()外面。

当我们打印这foo()里面的变量,它输出 local x: 10,这是调用了局部范围的变量。

同样的,当我们打印foo()外面的变量,它输出global x: 5,这是调用了全局范围的变量。


Nonlocal Variables

Nonlocal variable are used in nested function whose local scope is not defined. This means, the variable can be neither in the local nor the global scope.

Let's see an example on how a global variable is created in Python.

We use nonlocal keyword to create nonlocal variable.

非局部变量

非局部变量使用在局部范围不定义的内置函数里,这意思是,变量不在局部范围也不在全局范围。

让我们看一个例子怎样创建一个全局变量。

我们使用nonlocal关键字去创建非局部变量。


Example 6: Create a nonlocal variable

def outer():
    x = "local"
    
    def inner():
        nonlocal x
        x = "nonlocal"
        print("inner:", x)
    
    inner()
    print("outer:", x)

outer()

 

When we run the code, the will output be:

inner: nonlocal
outer: nonlocal

In the above code there is a nested function inner(). We use nonlocal keyword to create nonlocal variable. The inner() function is defined in the scope of another function outer().

Note : If we change value of nonlocal variable, the changes appears in the local variable.


例子6:创建一个非局部变量

 

def outer():
    x = "local"
    def inner():
        nonlocal x
        x = "nonlocal"
        print("inner :",x)
    inner()
    print("outer :",x)

outer()

当我们运行代码,输出结果为:

inner : nonlocal
outer : nonlocal

 以上代码在一个inner()内置函数中,我们使用nonlocal关键字去创建一个非局部变量。这inner()函数是定义在outer()函数范围里。

注意:如果我们改变非局部变量的值,改变在局部变量中。

;