×

# 草根学Python（十五） 闭包（解决一个需求了解闭包流程）

``````time = 0

def insert_time(min):
time = time + min
return  time

print(insert_time(2))
print(insert_time(10))
``````

``````UnboundLocalError: local variable 'time' referenced before assignment
``````

``````time = 0

def insert_time(min):
global  time
time = time + min
return  time

print(insert_time(2))
print(insert_time(10))
``````

``````2
12
``````

``````time = 0

def study_time(time):
def insert_time(min):
nonlocal  time
time = time + min
return time

return insert_time

f = study_time(time)
print(f(2))
print(time)
print(f(10))
print(time)
``````

``````2
0
12
0
``````

Python 闭包解决

``````time = 0

def study_time(time):
def insert_time(min):
nonlocal  time
time = time + min
return time

return insert_time

f = study_time(time)
print(f.__closure__)
print(f(2))
print(time)
print(f.__closure__[0].cell_contents)
print(f(10))
print(time)
print(f.__closure__[0].cell_contents)
``````

``````(<cell at 0x0000000000410C48: int object at 0x000000001D6AB420>,)
2
0
2
12
0
12
``````

20171204192251900.gif
【Python】