zoukankan      html  css  js  c++  java
  • python 装饰器之应用示例

    import time
    import hashlib
    import pickle
    import threading
    
    #装饰函数缓存应用
    
    cache ={}
    
    def is_obsolete(entry,duration):
        return time.time() - entry['time']>duration
    
    def compute_key(function,args,kw):
        key = pickle.dumps((function.__name__,args,kw))
        return hashlib.sha1(key).hexdigest()
    
    def momoize(duration=10):
        def __momoize(function):
            def __momoize(*args,**kw):
                key = compute_key(function,args,kw)
                #是否已经拥有了它?
                if(key in cache and not is_obsolete(cache[key],duration)):
                    print('we got a winner')
                    return cache[key]['value']
                #计算
                result =function(*args,**kw)
                #保存结果
                cache[key] ={
                    'value':result,
                    'time':time.time()
                }
                return result
            return __momoize
        return __momoize
    
    @momoize(5)
    def very_very_complex_stuff(a,b):
        #如果在执行计算时计算机过热
        #请终止程序
        return a + b
    
    # very_very_complex_stuff(1,1)
    # very_very_complex_stuff(2,2)
    # very_very_complex_stuff(3,3)
    # very_very_complex_stuff(4,4)
    # print(cache)
    # time.sleep(5)
    # very_very_complex_stuff(1,1)
    # very_very_complex_stuff(2,2)
    # very_very_complex_stuff(3,3)
    # very_very_complex_stuff(4,4)
    # print(cache)
    
    
    #代理
    
    class User(object):
        def __init__(self,roles):
            self.roles =roles
    
    class Unauthorized(Exception):
        pass
    
    def protect(role):
        def _protect(function):
            def __protect(*args,**kw):
                user = globals().get('user')
                if(user is None or role not in user.roles):
                    raise Unauthorized("I wo'nt tell you")
                return function(*args,**kw)
            return __protect
        return _protect
    
    tarek =User(('admin','user'))
    bill =User(('user'))
    
    class Mysecrets(object):
        @protect('admin')
        def waffle_recipe(self):
            print('user tons of butter!')
        
    
    # these_are = Mysecrets()
    # user = tarek
    # these_are.waffle_recipe()
    
    #上下文
    
    from threading import RLock
    lock =RLock()
    
    def synchronized(function):
        def _synchronized(*args,**kw):
            lock.acquire()
            try:
                return function(*args,**kw)
            finally:
                lock.release()
            return _synchronized
    
    @synchronized
    def thread_safe():
        pass
    
    
    class ContextIllustration:
        def __enter__(self):
            print('entering context')
        
        def __exit__(self,exc_type,exc_value,traceback):
            print('leaving context')
    
            if exc_type is None:
                print('with no error')        
            else:
                print('with an error (%s)'%exc_value)
    
    # with ContextIllustration():
    #      print('inside')
    
    
    from contextlib import contextmanager
    
    @contextmanager
    def contextillustration():
        print('entering context')
        try:
            yield
        except Exception as e:
            print('leaving context')
            print('with an error (%s)'%e)
            raise
        else:
            print('leaving context')
            print('with no error')          
    
    with contextillustration():
        print('inside')
    
    
    for number in range(1):
        break
    else:   
       print('no break')
    

      

  • 相关阅读:
    我的书单
    算法面试 字符串全排列
    各种算法面试简介--面试用一句话陈述
    逻辑回归 面试
    EM算法 小结
    python实现 单链表的翻转
    Transformer模型总结
    逻辑回归原理 面试 Logistic Regression
    XGBoost的优点
    python-解决pip安装速度慢的问题--豆瓣镜像
  • 原文地址:https://www.cnblogs.com/ms_senda/p/11973938.html
Copyright © 2011-2022 走看看