qiuyouzhi 发表于 2020-3-23 10:06:27

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

一个账号 发表于 2020-3-23 10:50:06

nonlocal 是关键字,怎么会是语句

像 nonlocal var 才是语句

wuqramy 发表于 2020-3-23 11:03:43

有必要从淘帖中删除吗@qiuyouzhi

wangka 发表于 2020-3-23 11:06:38

他只不过是放在自己的淘贴罢了

qiuyouzhi 发表于 2020-3-23 11:10:44

wuqramy 发表于 2020-3-23 11:03
有必要从淘帖中删除吗@qiuyouzhi

没,keyword里面的都放进去吧

wuqramy 发表于 2020-3-23 11:28:45

qiuyouzhi 发表于 2020-3-23 11:10
没,keyword里面的都放进去吧

rocktang 发表于 2020-3-23 19:30:14

Python nonlocal ?

qiuyouzhi 发表于 2020-3-23 19:30:58

rocktang 发表于 2020-3-23 19:30
Python nonlocal ?

rocktang 发表于 2020-3-24 10:19:40

新手,请多指教!
页: [1]
查看完整版本: Python nonlocal