对比
In Python 3.x,
内部函数可以对外部函数中的局变量进行访问,但不能对他进行修改
如果想修改,you can use the nonlocal
keyword:
def outer():
string = ""
def inner():
nonlocal string
string = "String was changed by a nested function!"
inner()
return string
# 也不能写成:
# nonlocal string
# string = "String was changed by a nested function!"
# 否则会报错 ,同global关键字的使用一样
In Python 2.x,
内部函数不能对外部函数中的局变量进行访问,也不能修改
如果想访问和修改,you could
(1) use a list with a single element and overwrite that single element:
def outer():
string = [""]
def inner():
string[0] = "String was changed by a nested function!"
inner()
return string[0]
(2)use global keword
Python2 - Global Variables
Global Variables
Variables that are created outside of a function (as in all of the examples above) are known as global variables.
Global variables can be used by everyone, both inside of functions and outside.
Example
Create a variable inside a function, with the same name as the global variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
运行结果:
Python is fantastic
Python is awesome
The global Keyword
Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.
To create a global variable inside a function, you can use the global
keyword.
Example
If you use the global
keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x
# 注意不能直接在初始化的时候加global关键词,否则会报错
# SyntaxError: invalid syntax
# global x = "ss"
运行结果:
Python is fantastic
Also, use the global
keyword if you want to change a global variable inside a function.
Example
To change the value of a global variable inside a function, refer to the variable by using the global
keyword:
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
运行结果:
Python is fantastic