Discuss / Python / 参考一下哈,注释是根据自己理解写的

参考一下哈,注释是根据自己理解写的

Topic source

def createCounter():

    ax = 0

    def couter():

        nonlocal ax # 当内部函数调用外部函数局部变量时,需要声明

        ax += 1 

        return ax 

    return couter

if __name__ == '__main__':

    counterA = createCounter() # 得到了couter这个函数,函数内部绑定了ax这个局部变量

    counterB = createCounter()

    print(counterA(), counterA(), counterA(), counterA(), counterA()) # 每次调用couter函数时,局部变量内部自己做运算

    if [counterB(), counterB(), counterB(), counterB()]  == [1, 2, 3, 4]:

        print('测试通过')

    else:

        print('测试失败')


  • 1

Reply