def func(x):
print ('X in the beginning of func(x): ', x)
x = 2
print ('X in the end of func(x): ', x)
x = 50func(x)print ('X after calling func(x): ', x)
输出:
X in the beginning of func(x): 50
X in the end of func(x): 2
X after calling func(x): 50
在 Python 的函数定义中,可以给变量名前加上 global 关键字,这样其作用域就不再局限在函数块中,而是全局的作用域。
通过 global 改写开始的例子:
def func():
global x print ('X in the beginning of func(x): ', x)
x = 2
print ('X in the end of func(x): ', x)
x = 50func()print ('X after calling func(x): ', x)
输出:
X in the beginning of func(x): 50
X in the end of func(x): 2
X after calling func(x): 2
函数 func 不再提供参数调用。而是通过 global x 告诉程序:这个 x 是一个全局变量。于是函数中的 x 和外部的 x 就成为了同一个变
def func():
print ('X in the beginning of func(x): ', x) # x = 2
print ('X in the end of func(x): ', x)
x = 50func()print ('X after calling func(x): ', x)
输出:
X in the beginning of func(x): 50
X in the end of func(x): 50
X after calling func(x): 50
def func(x):
print ('X in the beginning of func(x): ', x)
x = 2
print ('X in the end of func(x): ', x)
x = 50func(x)print ('X after calling func(x): ', x)
输出:
X in the beginning of func(x): 50
X in the end of func(x): 2
X after calling func(x): 50
在 Python 的函数定义中,可以给变量名前加上 global 关键字,这样其作用域就不再局限在函数块中,而是全局的作用域。
通过 global 改写开始的例子:
def func():
global x print ('X in the beginning of func(x): ', x)
x = 2
print ('X in the end of func(x): ', x)
x = 50func()print ('X after calling func(x): ', x)
输出:
X in the beginning of func(x): 50
X in the end of func(x): 2
X after calling func(x): 2
函数 func 不再提供参数调用。而是通过 global x 告诉程序:这个 x 是一个全局变量。于是函数中的 x 和外部的 x 就成为了同一个变
def func():
print ('X in the beginning of func(x): ', x) # x = 2
print ('X in the end of func(x): ', x)
x = 50func()print ('X after calling func(x): ', x)
输出:
X in the beginning of func(x): 50
X in the end of func(x): 50
X after calling func(x): 50