标签:未使用 ssi sign glob span var bsp oba pytho
以下实例都是通过执行以下代码,需要把以下执行代码放在后面实例代码的后面。
a = outer_func()
print("call a()") a() a() a() b = outer_func()
print("call b()") b() b() b()
def outer_func(): count = 3 def inner_func(): count += 1 print("count", count) return inner_func #output>>> # count += 1 #UnboundLocalError: local variable ‘count‘ referenced before assignment
def outer_func(): count = 3 def inner_func(): nonlocal count count += 1 print("count", count) return inner_func # output>>> # call a() # count 4 # count 5 # count 6 # call b() # count 4 # count 5 # count 6
def outer_func(): count = 3 def inner_func(): global count count += 1 print("count", count) return inner_func # output>>> # count += 1 # NameError: name ‘count‘ is not defined
count = 3 def outer_func(): def inner_func(): global count count += 1 print("count", count) return inner_func # output>>> # call a() # count 4 # count 5 # count 6 # call b() # count 7 # count 8 # count 9
[TimLinux] Python nonlocal和global的作用
标签:未使用 ssi sign glob span var bsp oba pytho
原文地址:https://www.cnblogs.com/timlinux/p/9193222.html