当前位置 博文首页 > 文章内容

    python 牛逼的functools.py

    作者: 栏目:未分类 时间:2020-07-07 9:02:31

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!




    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


    待加入