python 装饰器之应用示例
2024-08-27 08:56:31
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')
最新文章
- @import与link
- 遇到 Error creating the Web Proxy specified in the 'system.net/defaultProxy' configuration section的解决办法
- Ajaxadr ajax跨域请求crossdomain
- shader 的 nounroll
- javascript基础知识--函数定义
- AndroidSdk下载地址和环境变量配置
- iOS/iPhone 程序文件目录结构以及启动流程
- selenide小白教程
- mov指令具体解释
- 【机器学习】Iris Data Set(鸢尾属植物数据集)
- Python算法练习--把搜索树转成双向链表
- 20175236 JAVA MyCP(课下作业)
- ActiveMQ使用
- 【Windows】Windows中解析DOS的for命令使用
- 临时调用call()与apply()方法
- Oracle数据库基本常用命令汇总
- centos linux系统日常管理复习 CPU物理数逻辑核数,iftop ,iotop ,sar ,ps,netstat ,一网卡多IP,mii-tool 连接,ethtool速率,一个网卡配置多个IP,mii-tool 连接,ethtool速率 ,crontab备份, 第十八节课
- ASP.net/C#中如何调用动态链接库DLL
- R3—日期处理
- 洛谷p3369 treap