使用了c语言实现的函数
partial
可能的实现方式
def partial(func, *args, **keywords):
def newfunc(*fargs, **fkeywords):
newkeywords = keywords.copy()
newkeywords.update(fkeywords)
return func(*(args + fargs), **newkeywords)
newfunc.func = func
newfunc.args = args
newfunc.keywords = keywords
return newfunc
reduce
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 即 ((((1+2)+3)+4)+5)
cmp_to_key
把老形式的比较函数转换为key函数
(需要接收新形式key函数的函数:sorted min max heapq itertools.groupby)
老形式的比较函数:
接收两个参数,比较他们,返回-1 0 1这样来确定。
sorted(iterable, key=cmp_to_key(locale.strcoll)) # locale-aware sort order
total_ordering
包裹的类只要定义一个或多个比较函数即可生成出其余的函数来
lt, le, gt, ge 这几个函数必须要定义一个
使用
@total_ordering
class Student:
def __eq__(self, other):
return ((self.lastname.lower(), self.firstname.lower()) ==
(other.lastname.lower(), other.firstname.lower()))
def __lt__(self, other):
return ((self.lastname.lower(), self.firstname.lower()) <
(other.lastname.lower(), other.firstname.lower()))
update_wrapper
更新装饰器的属性使得装饰器像原来函数一样
源码
WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')
WRAPPER_UPDATES = ('__dict__',)
def update_wrapper(wrapper,
wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
for attr in assigned:
setattr(wrapper, attr, getattr(wrapped, attr))
for attr in updated:
getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
return wrapper
wrapper为装饰器,wrapped为被装饰的函数,assigned为赋值,updated为更新
wraps
wraps就是使用partial实现的快捷方式,用于装饰器的
def wraps(wrapped[, assigned][, updated]):
return partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)
例子
>>> from functools import wraps
>>> def my_decorator(f):
... @wraps(f)
... def wrapper(*args, **kwds):
... print 'Calling decorated function'
... return f(*args, **kwds)
... return wrapper
@my_decorator
... def example():
... """Docstring"""
... print 'Called example function'
...
>>> example()
Calling decorated function
Called example function
>>> example.__name__
'example'
>>> example.__doc__
'Docstring'
使用wraps会自动把docstr和funcname用起来