好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

关于Python中functools模块函数解析

这篇文章主要介绍了关于Python中functools模块函数解析,分别讲解了functools.cmp_to_key,functools.total_ordering,functools.reduce,functools.partial,functools.update_wrapper和functools.wraps的用法,需要的朋友可以参考下

@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())) 
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 
>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.doc = 'Convert base 2 string to an int.'
>>> basetwo('10010')
18 
>>> 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' 

如果不使用这个函数,示例中的函数名就会变成 wrapper ,并且原函数 example() 的说明文档(docstring)就会丢失。

以上就是关于Python中functools模块函数解析的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于关于Python中functools模块函数解析的详细内容...

  阅读:39次