Discuss / Python / list 和int 变量作用域不同

list 和int 变量作用域不同

Topic source

本地的Yoyo

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

def createCounter():

# list 可以在内外2个函数中直接使用

    i=[0]

    def counter():

        i[0]=i[0]+1

        return i[0]

    return counter

CountA=createCounter();

print (CountA(),CountA(),CountA(),CountA(),CountA())

CountB=createCounter();

print (CountB(),CountB(),CountB(),CountB())

def createCounterB():

#变量在两个函数中有不同的作用域,要么都声明为global,要么将内部变量声明为nonlocal

    global total

    total=0

    def counter():

        global total

        total = total+1

        return total

    return counter

CountA=createCounterB();

print (CountA(),CountA(),CountA(),CountA(),CountA())

CountB=createCounterB();

print (CountB(),CountB(),CountB(),CountB())


  • 1

Reply