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. 使用RestTemplate进行服务调用的几种方式

    首先我们在名为MSG的服务中定义一个简单的方法 @RestController public class ServerController { @GetMapping("/msg" ...

  2. ListView控件的理解——自洽理论

    写在前面的话: *标题中已经说明,是自洽理论.因此,有几率会有理解错误.但是,你不可以因此骂我. -我这个人经不起别人的批评,如果你批评我,我就,我就.... ## <第一行代码>读书笔记 ...

  3. 计算机网络--TCP协议深入理解

    在近期学习计算机网络的过程中,由于知识点过于零散,琐碎,从而学习起来痛苦不堪,此贴只是总结了基于传输层的TCP协议相关的知识细节,并加入一点自己的理解,并无创新,若有理解不当之处,敬请提出,感谢! 首 ...

  4. Linux下交换文件说明

    vi写文件,没有保存就关闭,会自动生成一个后缀为.swp的交换文件(隐藏文件),保存了前面写的内容 先利用R恢复,在删除这个交换文件 涉及到的命令 ls –a rm .xxx.swap -rf 

  5. Go实战--golang中使用redis(redigo和go-redis/redis)

    开源库redigo的使用 github地址: https://github.com/garyburd/redigo 文档地址: http://godoc.org/github.com/garyburd ...

  6. oracle笔记之计算年龄、工龄和TRUNC

    方法一:利用months_between 函数计算 SELECT TRUNC(months_between(sysdate, birthday)/12) AS agefrom dual; 方法二:日期 ...

  7. 关于window.location.hash的理解及其应用(转)

    原文1:https://blog.csdn.net/zhuchuji/article/details/50736360 原文2(window.location.href和window.location ...

  8. sqlserver导入Excel数据 总是报错:错误 0xc020901c: 数据流任务 1: 输出“Excel 源输出”(55) 上的 输出列“T2”(64) 出错。返回的列状态是:“文本被截断,或者一个或多个字符在目标代码页中没有匹配项

    在网络上搜索解决办法,解决办法是把excel导入到access数据库中,再把access数据库导入到sqlsever中,公司机器上不让安装office工具,问了一个同事得到的回答是把数据中很长的那行数 ...

  9. SVN_05用戶管控

    安全性设置 [1]在左侧的User上点击右键 输入上面的信息,点击OK,我们就创建一个用户了. 说明:注意到了下面图中的Groups,是的,也可以先创建组,把用户添加到各个组中,然后对组进行授权,操作 ...

  10. MyBatis 常用词汇含义

    JDBC:java Data Base  Connection(Java与数据库连接): ORM:Object Relational Mapping(对象关系映射,简称ORM,或者O/RM,或者O/M ...