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

  

python 装饰器之应用示例的更多相关文章

  1. Python装饰器之functools.wraps的作用

    # -*- coding: utf-8 -*- # author:baoshan def wrapper(func): def inner_function(): pass return inner_ ...

  2. Python装饰器之 property()

    1. 何为装饰器? 官方定义:装饰器是一个很著名的设计模式,经常被用于有切面需求的场景,较为经典的有插入日志.性能测试.事务处理等.装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量函数 ...

  3. Python 装饰器之 functools.wraps

    在看 Bottle 代码中看见 functools.wraps 这种用法. def make_default_app_wrapper(name): """ Return ...

  4. python装饰器之函数作用域

    1.函数作用域LEGB L:local函数内部作用域 E:enclosing函数内部与内嵌函数之间 G:global全局作用域 B:build-in内置作用域 passline = 60 def fu ...

  5. python装饰器之使用情景分析

    http://blog.csdn.net/yueguanghaidao/article/details/10089181

  6. Python装饰器详解

    python中的装饰器是一个用得非常多的东西,我们可以把一些特定的方法.通用的方法写成一个个装饰器,这就为调用这些方法提供一个非常大的便利,如此提高我们代码的可读性以及简洁性,以及可扩展性. 在学习p ...

  7. Python三大器之装饰器

    Python三大器之装饰器 开放封闭原则 一个良好的项目必定是遵守了开放封闭原则的,就比如一段好的Python代码必定是遵循PEP8规范一样.那么什么是开放封闭原则?具体表现在那些点? 开放封闭原则的 ...

  8. python 装饰器、递归原理、模块导入方式

    1.装饰器原理 def f1(arg): print '验证' arg() def func(): print ' #.将被调用函数封装到另外一个函数 func = f1(func) #.对原函数重新 ...

  9. 回顾Python装饰器

    函数装饰器(function decorator)可以对函数进行“标注”,给函数提供更多的特性. 在理解装饰器之前需要理解闭包(closure).Python3.0 引入了保留关键字 nonlocal ...

随机推荐

  1. MySQL 索引最佳实践

    原文请关注 这里 这是 文章 的翻译,在翻译过程中,会对其中涉及到的语句加上一些个人理解以及 SQL 语句的执行,并进行特别的标注. 1. 你做了一个很棒的选择,因为: 对于普通开发者和 DBA,理解 ...

  2. Spring 中的统一异常处理

    在具体的SSM项目开发中,由于Controller层为处于请求处理的最顶层,再往上就是框架代码的.因此,肯定需要在Controller捕获所有异常,并且做适当处理,返回给前端一个友好的错误码. 不过, ...

  3. 以环形角度理解php数组索引

    array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] ) : ...

  4. 面试题之web访问突然延迟问题

    前言 面试官经常会问平时访问正常的网页突然变慢是什么原因引起的,说明下你排查的思路:我认为这种问题很能考察一个人的综合知识面,既能融通的贯彻知识点,也能展看对每个知识点进行详细的考问. 下面我按我自己 ...

  5. Spring Boot集成Junit测试

    添加依赖: 在测试类上添加注解:

  6. Ubuntu下apt-get命令详解(转)

    原文:https://www.cnblogs.com/liyu925/p/6100388.html

  7. 1.MVC基础-初识MVC,与WebForm比较

    1.Net WebForm的开发模式

  8. K2 BPM_采购端到端解决方案,激活合规采购新动能_十年专注业务流程管理系统

    「方案背景」企业管理标准化演进之路 企业的成长离不开标准化,企业的可持续发展更离不开标准化.随着市场竞争的日趋激烈,标准化已经成为企业参与市场竞争的战略性手段,也成为企业可持续发展的重要手段.聚焦到采 ...

  9. 6.JUC之ReentrantReadWriteLock

    一.概述: Java纪年1.5年,ReentrantReadWriteLock诞生于JUC,此后,国人一般称它为读写锁.人如其名,他就是一个可重入锁,同时他还是一个读写锁 a)跟ReentrantLo ...

  10. jmeter安装,汉化

    下载完成后打开bin文件,选择jmeter.properties打开,搜索language,修改成zh_CN,汉化jmeter,记得去掉前面的#号,然后保存,修改完配置文件后需要重启jmeter 用的 ...