- 浏览: 241895 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (127)
- vim (3)
- python (44)
- pymysql (1)
- mysql (9)
- macvim (1)
- erlang (3)
- twisted (0)
- tornado (5)
- django (7)
- postgresql (5)
- sql (1)
- java (7)
- tech (4)
- cache (1)
- lifestyle (3)
- html (1)
- ubuntu (2)
- rabbitmq (1)
- algorithm (8)
- Linux (4)
- Pythonista (1)
- thread (1)
- sort (6)
- 设计模式 (1)
- search (1)
- Unix (6)
- Socket (3)
- C (2)
- web (1)
- gc (1)
- php (10)
- macos (1)
最新评论
-
2057:
这个程序有bug。
查找算法学习之二分查找(Python版本)——BinarySearch -
dotjar:
NB
一个Python程序员的进化[转]
Closure:如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure)。它只不过是个"内层"的函数,由一个名字(变量)来指代,而这个名字(变量)对于“外层”包含它的函数而言,是本地变量。
demo:
详细例子可见http://ivan.truemesh.com/archives/000411.html
Q:Decorators are an example of closures?
demo:
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__.
源码你会发现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/
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/
发表评论
-
macos 10.9.2 clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command
2014-03-25 19:13 1725方法总是有的,当然需要你去寻找。 当然如果花费太多的时间在一件 ... -
PostgreSQL psycopg2:IndexError: tuple index out of range
2014-01-09 17:04 2189Postgresql psycopg2使用like查询的时候 ... -
Python 迭代器和生成器
2013-10-15 23:09 2810迭代器 迭代器只不过是一个实现迭代器协议的容器对象。它基于两个 ... -
Python时间模块
2013-10-15 23:03 3426time模块 时间模块中最常用的一个函数就是获取当前时间的函数 ... -
Python装饰器
2013-10-15 22:59 1510编写自定义装饰器有许多方法,但最简单和最容易理解的方法是编写一 ... -
python list
2013-10-15 22:56 1214简单总结以及整理如下: >>> dir( ... -
Python Excel
2013-09-10 17:21 933安装lib easy_install xlrd def ... -
排序算法学习(python版本)之堆排序(HeapSort)
2013-07-01 22:54 1959Contains: 堆排序以及堆排序的应用 堆排序(Heaps ... -
python range xrange
2013-06-25 23:30 1106引用Help on built-in function ran ... -
python class
2013-06-25 00:54 1788引用类是创建新对象类 ... -
AttributeError: 'module' object has no attribute 'SendCloud'
2013-06-05 11:46 7020网上查了下 意思是说你命名的文件名不能和lib重名,这样会导 ... -
python string
2013-05-07 23:44 2161如果这就是字符串,这本来就是字符串 首先看下字符串的方法 ... -
Python property
2013-03-29 19:56 0由于之前有总结过,可以参考http://2057.iteye. ... -
python tips
2013-03-28 23:57 8471、enum #!/usr/bin/env python ... -
python decorators
2013-03-28 23:36 1325Contains: 1、decorators 2、funct ... -
Python map、filter,reduce介绍
2013-03-28 22:02 12441、filter(function,iterable) 引用C ... -
Python __new__ 、__init__、 __call__
2013-03-26 23:49 5295Contains: __new__: 创建对象时调用,返回当 ... -
Python socket简介
2013-03-25 23:42 2117自豪地使用dir和help. Python 2.7.2 ( ... -
Tornado ioloop源码简析
2013-03-21 00:18 2801#!/usr/bin/env python #-*-en ... -
Tornado httpserver 源码简析
2013-03-17 01:49 1744整个流程就是创建一个socket socket.socket ...
相关推荐
Function decorators and closures Part IV. Object Oriented Idioms Chapter 8. Object references, mutability and recycling Chapter 9. A Pythonic object Chapter 10. Sequence hacking, hashing and slicing...
Python对话Closures in Python支持材料。 谈话的目的是向观众介绍一般的封闭剂。 演示还包括来自其他语言(例如Java,C#或Javascript)的示例。 滑梯 在根文件夹中检出pycon2017-closures.pdf 。 资料夹结构 python...
Python ZTM备忘单 :laptop: :... 函数: Functions , Lambda , Comprehensions , Map,Filter,Reduce , Ternary , Any,All , Closures , Scope 高级Python: Modules , Iterators , Generators , Decorat
很多初次接触到python的小伙伴可能并不理解闭包是什么,为什么有闭包,闭包有什么用,那么今天博主就从这三点来为大家讲解一下python的闭包 一、闭包是什么 官方定义: 在计算机科学中,闭包(英语:Closure),又称词法...
搞不清楚在闭包(closures)中Python是怎样绑定变量的 看这个例子: >>> def create_multipliers(): ... return [lambda x : i * x for i in range(5)] >>> for multiplier in create_multipliers(): ... print ...
closures or blocks) to work with collections, but may be challenged with its static, generic-supporting type system. For these and any other developers who want to learn how to develop in the Scala ...
Compare Swift with Objective-C, JavaScript, Python, Ruby, and C Collect data with arrays and dictionaries, and store it with variables and constants Group commonly-used code into functions for easy ...
Go语言的主要目标是兼具Python等动态语言的开发速度和C/C++等编译型语言的性能与安全性。Go语言设计良好,执行性能高,可以在不损失应用程序性能的情况下降低代码的复杂性。 Go语言的语法与C相近,但功能上有内存...
Groovy向Java添加了许多Ruby和Python脚本语言的特性. Groovy的特性包括动态类型(dynamic typing), 闭包(closures),简单对象导航( easy object navigation)和更加简洁的Lists和Maps语法.所有这些特性和其他一些...
Apple developed Swift to address the limitations of Objective-C, and add features found in more complex languages like Python. The results is simpler, cleaner, more expressive code with automatic ...
Chapter 2: Functions, Closures, And Modules Chapter 3: Data Structures And Manipulation Chapter 4: Object-Oriented Javascript Chapter 5: Javascript Patterns Chapter 6: Testing And Debugging Chapter 7:...
(6)、Python (<1)、Web 技术 (<1) iOS 框架: UIKit、Foundation、RxSwift、CoreLocation、MapKit、CoreData、AVFoundation、HealthKit、WebKit 和 Realm、XCTest、OHTTPStubs、RxSwift、Interstellar...
Benefit from new features in C++14, such as auto variables and closures., Who this book is for, Practical C++ Financial Programming is for professionals or advanced students who have interest in ...