Python nonlocal
本帖最后由 qiuyouzhi 于 2020-3-23 11:01 编辑Python nonlocal
语法:
nonlocal varname
实例:
>>> 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 nonlocal 是关键字,怎么会是语句
像 nonlocal var 才是语句 有必要从淘帖中删除吗@qiuyouzhi 他只不过是放在自己的淘贴罢了 wuqramy 发表于 2020-3-23 11:03
有必要从淘帖中删除吗@qiuyouzhi
没,keyword里面的都放进去吧 qiuyouzhi 发表于 2020-3-23 11:10
没,keyword里面的都放进去吧
好 Python nonlocal ? rocktang 发表于 2020-3-23 19:30
Python nonlocal ?
? 新手,请多指教!
页:
[1]