码迷,mamicode.com
首页 > 编程语言 > 详细

python 牛逼的functools.py

时间:2020-07-07 09:53:41      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:try   code   写法   def   function   ESS   pass   wrap   cep   


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

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


待加入


python 牛逼的functools.py

标签:try   code   写法   def   function   ESS   pass   wrap   cep   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!