Python中nonlocal的用法
1 class Text: 2 def __init__(self): 3 pass 4 def big(self): 5 n, m = 0, 0 6 def a(): 7 nonlocal n 8 n += 1 9 print(n) 10 if n == 1: 11 print('one') 12 elif n == 2: 13 print('two') 14 a() 15 a() 16 if __name__ == '__main__': 17 text = Text() 18 text.big()
打印结果:
1
one
2
two
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步