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('测试失败')
Sign in to make a reply
原来我们90未满
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('测试失败')