zly! 发表于 2021-8-17 16:49:27

python课后习题

def funX():
    x = 5
    def funY():
      nonlocal x
      x += 1
      return x
    return funY

a = funX()
print(a())
print(a())
print(a())

为什么会打印:
6
7
8

青出于蓝 发表于 2021-8-17 16:49:28

nonlocal关键字声明x只作用于嵌套函数funY中。所以funY以外的对于变量x的赋值就不起作用了。

青雨V1 发表于 2021-8-17 17:01:51

nonlocal x
每次都会修改x的值(⊙o⊙)…

大马强 发表于 2021-8-17 17:12:27

那么为什么不呢
nonlocal 语句给了内部函数修改外部函数变量的权限
a()相当于调用了funY(),funY()修改了变量x,所以才会6 7 8

hornwong 发表于 2021-8-17 20:23:44

{:5_95:}
页: [1]
查看完整版本: python课后习题