|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
B站46讲小甲鱼降到了nonlocal的用法,感觉不是很理解。百度了一下,感觉讲的也是玄之又玄的。其实我觉得很简单啦,以下面的代码为例。
原来“x, y”只能作用于函数outer(),地盘就在第一层函数,在第二层提他没用,见代码1。使用nonlocal之后“x,y”的地盘扩大到了第二层,提他也有用,见代码2。
代码1:
- def outer():
- x=0
- y=0
- def inner(x1, y1):
- x+=x1
- y+=y1
- print(f"Now, x={x}, y={y}")
- return inner
- move = outer()
- move(1, 2)
- Traceback (most recent call last):
- File "<pyshell#76>", line 1, in <module>
- move(1, 2)
- File "<pyshell#74>", line 5, in inner
- x+=x1
- UnboundLocalError: cannot access local variable 'x' where it is not associated with a value
复制代码
代码2:
- >>> def outer():
- ... x = 0
- ... y = 0
- ... def inner(x1, y1):
- ... nonlocal x, y
- ... x +=x1
- ... y +=y1
- ... print(f"现在, x = {x}, y = {y}")
- ... return inner
- ...
- >>> move = outer()
- >>> move(1, 2)
- 现在, x = 1, y = 2
- >>> move(-2, 2)
- 现在, x = -1, y = 4
复制代码
|
|