﻿ Python闭包的两个注意事项(推荐) - 军军小站|张军博客

# Python闭包的两个注意事项(推荐)

Python闭包函数所引用的外部自由变量是延迟绑定的。

Python

```
In [2]: def multipliers():
...:   return [lambda x: i * x for i in range(4)]
In [3]: print [m(2) for m in multipliers()]
[6, 6, 6, 6]
In [2]: def multipliers():
...:   return [lambda x: i * x for i in range(4)]
In [3]: print [m(2) for m in multipliers()]
[6, 6, 6, 6]
```

1) 生成闭包函数的时候立即绑定(使用函数形参的默认值):

Python

```
In [5]: def multipliers():
return [lambda x, i=i: i* x for i in range(4)]
...:
In [6]: print [m(2) for m in multipliers()]
[0, 2, 4, 6]
In [5]: def multipliers():
return [lambda x, i=i: i* x for i in range(4)]
...:
In [6]: print [m(2) for m in multipliers()]
[0, 2, 4, 6]
```

2) 使用functools.partial:

Python

```
In [26]: def multipliers():
return [functools.partial(lambda i, x: x * i, i) for i in range(4)]
....:
In [27]: print [m(2) for m in multipliers()]
[0, 2, 4, 6]
In [26]: def multipliers():
return [functools.partial(lambda i, x: x * i, i) for i in range(4)]
....:
In [27]: print [m(2) for m in multipliers()]
[0, 2, 4, 6]
```

Python

```
def foo(func):
free_value = 8
def _wrapper(*args, **kwargs):
old_free_value = free_value #保存旧的free_value
free_value = old_free_value * 2 #模拟产生新的free_value
func(*args, **kwargs)
free_value = old_free_value
return _wrapper
def foo(func):
free_value = 8
def _wrapper(*args, **kwargs):
old_free_value = free_value #保存旧的free_value
free_value = old_free_value * 2 #模拟产生新的free_value
func(*args, **kwargs)
free_value = old_free_value
return _wrapper
```

QQ号联系： 360901061

【本文对您有帮助就好】