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')
python 装饰器之应用示例的更多相关文章
- Python装饰器之functools.wraps的作用
# -*- coding: utf-8 -*- # author:baoshan def wrapper(func): def inner_function(): pass return inner_ ...
- Python装饰器之 property()
1. 何为装饰器? 官方定义:装饰器是一个很著名的设计模式,经常被用于有切面需求的场景,较为经典的有插入日志.性能测试.事务处理等.装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量函数 ...
- Python 装饰器之 functools.wraps
在看 Bottle 代码中看见 functools.wraps 这种用法. def make_default_app_wrapper(name): """ Return ...
- python装饰器之函数作用域
1.函数作用域LEGB L:local函数内部作用域 E:enclosing函数内部与内嵌函数之间 G:global全局作用域 B:build-in内置作用域 passline = 60 def fu ...
- python装饰器之使用情景分析
http://blog.csdn.net/yueguanghaidao/article/details/10089181
- Python装饰器详解
python中的装饰器是一个用得非常多的东西,我们可以把一些特定的方法.通用的方法写成一个个装饰器,这就为调用这些方法提供一个非常大的便利,如此提高我们代码的可读性以及简洁性,以及可扩展性. 在学习p ...
- Python三大器之装饰器
Python三大器之装饰器 开放封闭原则 一个良好的项目必定是遵守了开放封闭原则的,就比如一段好的Python代码必定是遵循PEP8规范一样.那么什么是开放封闭原则?具体表现在那些点? 开放封闭原则的 ...
- python 装饰器、递归原理、模块导入方式
1.装饰器原理 def f1(arg): print '验证' arg() def func(): print ' #.将被调用函数封装到另外一个函数 func = f1(func) #.对原函数重新 ...
- 回顾Python装饰器
函数装饰器(function decorator)可以对函数进行“标注”,给函数提供更多的特性. 在理解装饰器之前需要理解闭包(closure).Python3.0 引入了保留关键字 nonlocal ...
随机推荐
- SecureCRT系列:生成公私钥
SecureCRT下载地址:http://www.portablesoft.org/securecrt-securefx-legacy-versions/1.打开我们的SecureCRT客户端,点击t ...
- (三)shiro的认证
文章目录 认证思路 自定义用于登录检验的Realm的思路 代码实现 后记 认证思路 调用 SecurityUtils.getSubject() 方法,获取当前的 Subject 对象 : 调用 Sub ...
- nfs挂载文件
1. 安装必备插件 以防centos7默认没有启动nfs服务 yum -y install nfs-utils rpcbind # 启动 rpcbind 和配置开机自启动 systemctl sta ...
- Linux磁盘管理系列 — LVM和RAID
一.逻辑卷管理器(LVM) 1.什么是逻辑卷管理器(LVM) LVM是逻辑盘卷管理(Logical Volume Manager)的简称,它是Linux环境下对卷进行操作的抽象层. LVM是建立在硬盘 ...
- Z算法板子
给定一个串$s$, $Z$算法可以$O(n)$时间求出一个$z$数组 $z_i$表示$s[i...n]$与$s$的前缀匹配的最长长度, 下标从$0$开始 void init(char *s, int ...
- web开发工具flask中文英文书籍-持续更新
web开发工具flask中文英文书籍-持续更新 python测试开发_AI命理关注 0.9222018.11.10 07:48:43字数 625阅读 885 python测试开发项目实战-目录 pyt ...
- VC串口通讯,WriteFile或ReadFile没有任何返回??
别犯低级错误,一定要设置读写超时!!!
- Python遗传和进化算法框架(一)Geatpy快速入门
https://blog.csdn.net/qq_33353186/article/details/82014986 Geatpy是一个高性能的Python遗传算法库以及开放式进化算法框架,由华南理工 ...
- .net core 杂记:用Autofac替换内置容器
官方建议使用内置容器,但有些功能并不支持,如下: 属性注入 基于名称的注入 子容器 自定义生存期管理 Func<T> 支持 所以可以使用其他第三方IOC容器,如Autofac,下面为学习使 ...
- Centos6 r8192ce_pci
Centos6 r8192ce_pci # # yum install epel-release# yum-config-manager --enable rhui-REGION-rhel-serve ...