|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 qiuyouzhi 于 2020-3-23 11:01 编辑
Python nonlocal
语法:
实例:
- >>> def test():
- x = 5
- def test2():
- x *= x # 这样会报错
- return x
- return test2()
- >>> test()
- Traceback (most recent call last):
- File "<pyshell#11>", line 1, in <module>
- test()
- File "<pyshell#10>", line 6, in test
- return test2()
- File "<pyshell#10>", line 4, in test2
- x *= x # 这样会报错
- UnboundLocalError: local variable 'x' referenced before assignment
- >>> def test():
- x = 5
- def test2():
- y = 1
- y *= x # 这样就不会,因为并没有对x进行改变,只是访问
- return y
- return test2()
- >>> test()
- 5
- >>> def test():
- x = 5
- def test2():
- nonlocal x
- x *= x # 但你要是执意对x就行操作的话,就用nonlocal x
- return x
- return test2()
- >>> test()
- 25
复制代码 |
|