[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/Lovepython015/Python/master/Article/PythonBasis/python15/1.md [Back]  [Original]

 Python 


 2  2  10  12 




```Python
time = 0

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

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



 Python 

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

 Python 



 `global` ,

```Python
time = 0


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

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



```
2
12
```

 `time`  `time` 








```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(2))
print(time)
print(f(10))
print(time)
```

:

```
2
0
12
0
```

 `time` , `nonlocal` ,()

![](http://twowaterimage.oss-cn-beijing.aliyuncs.com/2019-10-14-Python%20%E9%97%AD%E5%8C%85%E8%A7%A3%E5%86%B3.png)


 k








 ` __closure__`  cell cell  cell_contents 



```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)
```



```
(,)
2
0
2
12
0
12
```

 cell_contents ,





Web Proxy Viewer  |  New URL  |  Original Page