python 牛逼的functools.py

Posted 活到学到

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 牛逼的functools.py相关的知识,希望对你有一定的参考价值。


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的主要内容,如果未能解决你的问题,请参考以下文章

Python多重继承引发的问题——牛逼的super

Linux上安装python3.6 并创建虚拟环境 -----最牛逼的方法

Google推出了Python最牛逼的编辑器

200页!这可能是最牛逼的Python自学手册啦!

200页!这可能是最牛逼的Python自学手册啦!

200页!这可能是最牛逼的Python自学手册啦!