Discuss / Python / 老是把问题想复杂了

老是把问题想复杂了

Topic source

singcao

#1 Created at ... [Delete] [Delete and Lock User]
def createCounter():
    s = [0]
    def counter():
        s[0] = s[0] + 1
        return s[0]
    return counter

bdjkmxj

#2 Created at ... [Delete] [Delete and Lock User]

请教一下:

这里如果将s的类型由列表改为int后,为什么就需要在counter():里注明’nonlocal s‘:

def createCounter():
    s = 0
    def counter():
        nonlocal s
        s = s + 1
        return s
    return counter

而用您原来的方法写,为什么就不需要?

list作为全局变量是不需要声明的

lov1394_198

#4 Created at ... [Delete] [Delete and Lock User]

访问外部函数的不可变类型局部变量要加 nonlocal


  • 1

Reply