python 备忘(内置模块)牛逼的functools.py


functools.wraps

import functools

def auth(func):
    @functools.wraps(func)
    def inner(*args, **kwargs):
        if not session.get('user'):
            return redirect(url_for('login'))
        ret = func(*args, **kwargs)
        return ret
    return inner


@app.route('/index')
@auth
def index():
    return render_template('index.html', stu_dic=STUDENT_DICT)





functools.partial

#Flask中应用

request = functools.partial(_lookup_req_object,'request')
session = functools.partial(_lookup_req_object,'session')

functools.cmp_to_key

#unittest中应用
'''
loader.py
'''
sortTestMethodsUsing = staticmethod(util.three_way_cmp)

if self.sortTestMethodsUsing:
    testFnNames.sort(key=functools.cmp_to_key(self.sortTestMethodsUsing))

'''
key函数实际上就是class的构造函数(函数和类会被加括号调用或者实例化),实际上就是将要比较的对象(list中的对象)作为参数创建了两个cmp_to_key对象,
这两个cmp_to_key对象进行过运算符重载,是可以比较的,比较的规则就是传入的cmp所定义的规则。这样就实现了自定义排序规则了。
'''
'''
以冒泡算法举例:
takeSecond(testFnNames[0]) 和 takeSecond(testFnNames[1]) 比较进行一次排序。。。。
'''


'''
util.py
'''
def three_way_cmp(x, y):
    """Return -1 if x < y, 0 if x == y and 1 if x > y"""
    return (x > y) - (x < y)

'''
print(True-False) #结果是1 ,可以参考一下
'''

'''
functools.py
'''
#传入cmp函数,返回对象
def cmp_to_key(mycmp):
    #Convert a cmp= function into a key= function
    class K(object):
        __slots__ = ['obj']
        def __init__(self, obj):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        __hash__ = None
    return K

try:
    from _functools import cmp_to_key
except ImportError:
    pass

补充:
python3 list的sort方法

# 获取列表的第二个元素
def takeSecond(elem):
    return elem[1]
 
# 列表
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
 
# 指定第二个元素排序
random.sort(key=takeSecond)
 
# 输出类别
print '排序列表:', random

# 输出结果
排序列表:[(4, 1), (2, 2), (1, 3), (3, 4)]

'''
以冒泡算法举例:
takeSecond(random[0]) 和 takeSecond(random[1]) 比较进行一次排序。。。。
'''

原文地址:https://www.cnblogs.com/amize/p/13258849.html