kzh*_*kzh 5 python global-variables nested-function
以下代码:
x = 0
print "Initialization: ", x
def f1():
x = 1
print "In f1 before f2:", x
def f2():
global x
x = 2
print "In f2: ", x
f2()
print "In f1 after f2: ", x
f1()
print "Final: ", x
Run Code Online (Sandbox Code Playgroud)
打印:
Initialization: 0
In f1 before f2: 1
In f2: 2
In f1 after f2: 1
Final: 2
Run Code Online (Sandbox Code Playgroud)
有没有办法f2访问f1变量?
在Python 3中,您可以在f2中将x定义为非本地.
在Python 2中,您不能直接分配给f2中的f1的x.但是,您可以读取其值并访问其成员.所以这可能是一个解决方法:
def f1():
x = [1]
def f2():
x[0] = 2
f2()
print x[0]
f1()
Run Code Online (Sandbox Code Playgroud)