数据工程师

functools 模块详解

2017-03-08  本文已影响24人  苟雨

functool.reduce 方法是迭代的应用传入的方法用前面得到的值来作为输入,所以方法最好有两个以上的变量,不然就不能迭代了

import functools
def ad(x,y):
    return x*y
​
functools.reduce(ad,[2,3,4])
24

functools.partial 函数可以为函数提供定义好的输入变量,就像是函数的预定义变量一样,

In [27]:

def hello(one,two,three):
    if one:
        return two
    else:
        return three
    
par_func = functools.partial(hello,two='yes',three='no')
par_func(1)
Out[27]:
'yes'

functools.wraps 用这个函数定义函数的包装器,

In [33]:

from functools import wraps 
def my_decorator(f):
    @wraps(f)
    def wraper(*args,**kwds):
        print('calling decorators now')
        return f(*args,**kwds)
    return wraper
​
@my_decorator
def use_decorator():
    print('function use decotator')
    
use_decorator()
    
calling decorators now
function use decorator

functools.total_ordering 定义类的比较方式

In [35]:

from functools import total_ordering
@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()))
​
上一篇 下一篇

猜你喜欢

热点阅读