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 ...
随机推荐
- vector 使用pair对
pair是一种序偶结构<x,y> 如果我们希望使用pair但又不需要map对其排序,可以在vector中使用pair对 插入pair对使用make_pair<typename,typ ...
- PAT(B) 1027 打印沙漏(Java)
题目链接:1027 打印沙漏 (20 point(s)) 题目描述 本题要求你写个程序把给定的符号打印成沙漏的形状.例如给定17个"*",要求按下列格式打印 ***** *** * ...
- 文件类型分类:头文件dirent.h中定义的文件类型与linux内文件符号对应关系
头文件 dirent.h 定义了文件类型: enum{ DT_UNKNOWN = 0, //未知类型 DT_FIFO = 1, //first in, ...
- JPA 一对一 一对多 多对一 多对多配置
1 JPA概述 1.1 JPA是什么 JPA (Java Persistence API) Java持久化API.是一套Sun公司 Java官方制定的ORM 方案,是规范,是标准 ,sun公司自己并没 ...
- NOI2000 青蛙过河[递推]
也许更好的阅读体验 \(\mathcal{Description}\) 原题链接: Comet OJ 洛谷 大小各不相同的一队青蛙站在河左岸的石墩(记为A)上,要过到对岸的石墩(记为D)上去.河心有几 ...
- 多线程使用libcurl
curl默认情况下有两个地方是线程不安全的, 需要特殊处理, 1是curl_global_init 这个函数必须单线程调用, 2是默认多线程调用https会莫名其妙的挂掉, 以下是网上的解决方案 ht ...
- FLV 数据封装格式
https://www.cnblogs.com/chyingp/p/flv-getting-started.html https://blog.csdn.net/ai2000ai/article/de ...
- 微信开发者工具 关于no such file or directory
在新建页面中,保存后弹出 “ no such file or directory ” 错误 原因是打开了一个文件,然后在目录树中删除了它,但是这个被删除的页面依旧在打开状态,开发者工具在编译保存时由于 ...
- Linux-开机启动程序
尝试一下几种方法: 1.修改 /etc/rc.local文件. 在exit0 前添加启动命令 2.在/home/pi/.config/autostart/ 下添加.desktop 在.config ...
- 管理Linux软件——apt
参考:Ubuntu的apt命令详解 apt命令是一个功能强大的命令行工具,它与Ubuntu的高级打包工具(APT,Advanced Packaging Tool )配合使用,可以执行安装新软件包,升级 ...