python closures

本文深入探讨了Python中闭包的概念及其应用,并通过具体示例解析了装饰器的工作原理及其实现方式,同时介绍了functools模块中的wraps功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[b]Closure[/b]:如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure)。它只不过是个"内层"的函数,由一个名字(变量)来指代,而这个名字(变量)对于“外层”包含它的函数而言,是本地变量。
demo:

#-*-coding:utf-8-*-

class Employee(object):

def __init__(self,is_manager=False,salary=1000):
self.is_manager = is_manager
self.salary = salary

class Employees:
def __init__(self,employees):
self.employees = employees
def do(self,block):
for e in self.employees:
block.value(e)

def anonymous_function(employee):
if employee.is_manager:
employee.salary = 2000

def total_cost_of_managers(employees):
#TODO why not user total = 0 will raise Exception(UnboundLocalError: local variable 'total' referenced before assignment)?
total = [0]
def anonymous_function(employee):
if employee.is_manager:
total[0] = total[0]+employee.salary
map(anonymous_function, employees)
return total[0]

def total_cost_of_managers_2(employees):
total = [0]
class AnonymousClass:
def value(self, employee):
if employee.is_manager:total[0] = total[0]+employee.salary
employees.do(AnonymousClass())
return total[0]

def total_cost_of_managers_3(employees):
class AnonymousClass:
def __init__(self):
self.total = 0
def value(self, employee):
if employee.is_manager:self.total = self.total+employee.salary
block = AnonymousClass()
employees.do(block)
return block.total

def total_cost_of_managers_4(employees):
class AnonymousClass:
def __init__(self):
self.total = 0
def __call__(self, employee):
if employee.is_manager:self.total = self.total+employee.salary
block = AnonymousClass()
map(block,employees)
return block.total

def total_cost_of_managers_5(employees):
total = 0
for employee in employees:
if employee.is_manager:total = total+employee.salary
return total

employee = Employee()
employee.is_manager = True
employee2 = Employee()
employees = [employee,employee2]
#map(lambda e:e.is_manager and e.salary>1000 and e.salary+1000,employees)
map(anonymous_function,employees)
print 'total employee\'s salary is',employee.salary
print 'total manager\'s cost is',total_cost_of_managers(employees)
employees=Employees(employees)
print total_cost_of_managers_2(employees)
print total_cost_of_managers_3(employees)
print total_cost_of_managers_4([employee,employee2])
print total_cost_of_managers_5([employee,employee2])

详细例子可见[url]http://ivan.truemesh.com/archives/000411.html[/url]
[b]Q:Decorators are an example of closures?[/b]
demo:

#-*-coding:utf-8-*-
import functors
def foo(f):
@functools.wraps(f)
def wraps(*args,**kwargs):
print 'do something …'
return f(*args,**kwargs)
return wraps

@foo
class Bar:
def __init__(self):
self.name = 'foo is bar'

bar = Bar()
print bar.name


[b]Q:what does functools.wraps do?[/b]
functools.partial is a useful utility function that copies attributes from the wrapped function to the wrapping function.

The functools.wraps function is a nice little convenience function that makes the wrapper function (i.e., the return value from the decorator) look like the function it is wrapping. This involves copying/updating a bunch of the double underscore attributes—specifically__module__, __name__, __doc__, and __dict__.

def update_wrapper(wrapper,
wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Update a wrapper function to look like the wrapped function


wrapper is the function to be updated
wrapped is the original function
assigned is a tuple naming the attributes assigned directly
from the wrapped function to the wrapper function (defaults to
functools.WRAPPER_ASSIGNMENTS)
updated is a tuple naming the attributes of the wrapper that
are updated with the corresponding attribute from the wrapped
function (defaults to functools.WRAPPER_UPDATES)
"""
for attr in assigned:
setattr(wrapper, attr, getattr(wrapped, attr))
for attr in updated:
getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
# Return the wrapper so this can be used as a decorator via partial()
return wrapper


def wraps(wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Decorator factory to apply update_wrapper() to a wrapper function


Returns a decorator that invokes update_wrapper() with the decorated
function as the wrapper argument and the arguments to wraps() as the
remaining arguments. Default arguments are as for update_wrapper().
This is a convenience function to simplify applying partial() to
update_wrapper().
"""
return partial(update_wrapper, wrapped=wrapped,
assigned=assigned, updated=updated)


[b]源码你会发现wraps调用的是一个对partial(update_wrapper, ...)的简单包装。
partial主要是用来修改函数签名,使一些参数固化,以提供一个更简单的函数供以后调用 update_wrapper是wraps的主要功能提供者,它负责考贝原函数的属性,默认是:'__module__', '__name__', '__doc__', '__dict__'。[/b]
有关functools可以参考我之前的整理:
[url]http://2057.iteye.com/blog/1798472[/url]
详细的介绍closures以及问题可参考:
[url]http://blog.youkuaiyun.com/marty_fu/article/details/7679297[/url]
参考资料:
http://ivan.truemesh.com/archives/000392.html
http://ivan.truemesh.com/archives/000411.html
http://ivan.truemesh.com/archives/000425.html
http://feilong.me/2012/06/interesting-python-closures
http://en.wikipedia.org/wiki/Python_syntax_and_semantics
http://blaag.haard.se/Python-Closures-and-Decorators--Pt--1/
http://blaag.haard.se/Python-Closures-and-Decorators--Pt--2/
http://www.ibm.com/developerworks/cn/linux/l-cn-closure/index.html
http://stackoverflow.com/questions/233673/lexical-closures-in-python
http://stackoverflow.com/questions/308999/what-does-functools-wraps-do
http://stackoverflow.com/questions/2796855/python-closures-example-code
http://blogs.oucs.ox.ac.uk/inapickle/2012/01/05/python-decorators-with-optional-arguments/
### Python 闭包的概念 在 Python 中,闭包是指一个函数对象能够记住它被创建的作用域中的变量。即使这些作用域已经不可用了,闭包仍然可以访问它们。这种特性使得闭包成为一种强大的工具,用于封装状态并提供更灵活的功能设计。 当内部函数引用外部函数的局部变量时,就形成了闭包[^1]。需要注意的是,闭包不仅限于嵌套函数的情况;只要满足条件——即存在自由变量绑定到其所在环境,则该结构就可以称为闭包。 下面是一个简单的例子展示如何构建以及使用基本形式下的 python closures: ```python def outer_function(text): def inner_function(): print(text) return inner_function my_closure = outer_function('Hello World!') my_closure() # 输出 'Hello World!' ``` 在这个示例中, `outer_function` 返回了一个指向 `inner_function` 的引用而不是调用执行这个函数本身; 当我们之后通过变量名 (`my_closure`) 来触发此返回值的时候才会真正运行其中的内容. 另外值得注意的一点是关于修改外层作用域内的可变对象(比如列表或者字典), 我们可以直接对其进行更改而无需声明 global 或者 nonlocal 关键词. 下面给出一段代码说明这一现象: ```python def make_adder(x): y = [] def add(z): y.append(z+x) return sum(y) return add adder = make_adder(5) print(adder(3)) # 结果为8 print(adder(-2)) # 结果为6 (因为y=[8,-7], 所以sum=6) ``` 上述程序展示了闭包的一个重要应用领域—工厂模式,在这里每次调用都会累积之前的结果直到最终得到总和。 最后提醒一点就是如果尝试改变不可变得数值型参数则需要借助nonlocal关键字来进行操作了。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值