python变量作用域问题

# 代码1 正确
def make_counter(init):
    counter = [init]

    def inc(): counter[0] += 1
    def get(): return counter[0]

    return inc, get


increase, gain = make_counter(5)
increase()
print(gain())


# 代码2 报错
def make_counter(init):
    counter = init

    def inc(): counter += 1
    def get(): return counter

    return inc, get


increase, gain = make_counter(5)
increase()
print(gain())

为什么代码1没有问题,而代码2却报错?

这是内嵌函数变量作用范围的问题:
在内部函数中,只能对外部函数的局部变量进行访问,但不能进行修改。如果想要进行修改,必须放到容器(啥都可以放的数据类型就是容器类型)里面。
如果在内部函数内对外部的变量进行修改,函数会重新定义一个和外面的变量同名的变量,因此需要你重新定义。你报错就是因为你尝试修改外部变量的值,所以你要不就用nonlocal关键字,声明一下,或者就把数据放到容器里面。
 

# 代码2 报错
def make_counter(init):
    counter = init
 
    def inc(): 
        nonlocal counter
        counter += 1
    def get(): 
        return counter
 
    return inc, get
 
increase, gain = make_counter(5)
increase()
print(gain())

这里的nonlocal 和global基本是一样的

counter = [init]     counter = init  一个counter是列表,一个是int型,类型不一样,列表可变,int不行

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632