设为首页 收藏本站
查看: 548|回复: 0

[经验分享] python closures

[复制链接]

尚未签到

发表于 2017-4-21 08:10:03 | 显示全部楼层 |阅读模式
Closure:如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(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])
详细例子可见http://ivan.truemesh.com/archives/000411.html
Q:Decorators are an example of closures?
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

Q:what does functools.wraps do?
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)

源码你会发现wraps调用的是一个对partial(update_wrapper, ...)的简单包装。
partial主要是用来修改函数签名,使一些参数固化,以提供一个更简单的函数供以后调用 update_wrapper是wraps的主要功能提供者,它负责考贝原函数的属性,默认是:'__module__', '__name__', '__doc__', '__dict__'。

有关functools可以参考我之前的整理:
http://2057.iteye.com/blog/1798472
详细的介绍closures以及问题可参考:
http://blog.csdn.net/marty_fu/article/details/7679297
参考资料:
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/

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-367101-1-1.html 上篇帖子: python概览 下篇帖子: python crud
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表