面试题答案
一键面试-
体现的特性:这体现了Python变量作用域的闭包特性。闭包是指在一个函数内部定义的函数可以访问其外部函数的变量,即使外部函数已经执行完毕。
-
修改代码:
def outer():
x = 10
def inner():
nonlocal x
x = 20
print(x)
return inner
func = outer()
func()
- 修改后的结果:运行上述修改后的代码,会输出
20
。使用nonlocal
关键字声明x
表示x
不是一个新的局部变量,而是引用外部(但非全局)作用域中的x
变量,这样就可以在inner
函数中修改outer
函数中的x
变量的值。