首页 > 编程语言 > 详细

python 牛逼的functools.py

时间:2020-07-07 10:32:10      阅读:54      评论:0      收藏:0      [点我收藏+]

functools.wraps

# Flask CBV 写法
import functools
from flask import Flask, views

app = Flask(__name__)


def wrapper(func):
    @functools.wraps(func)
    def inner(*args, **kwargs):
        return func(*args, **kwargs)

    return inner


class UserView(views.MethodView):
    methods = [‘GET‘]
    decorators = [wrapper, ]

    def get(self, *args, **kwargs):
        return ‘GET‘

    def post(self, *args, **kwargs):
        return ‘POST‘


app.add_url_rule(‘/user‘, None, UserView.as_view(‘uuuu‘))

if __name__ == ‘__main__‘:
    app.run()

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))



‘‘‘
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)


‘‘‘
functools.py
‘‘‘
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)]

https://zhuanlan.zhihu.com/p/26546486


python 牛逼的functools.py

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!