python装饰器应用论文_python 装饰器之应用示例

news/2024/7/4 1:10:41

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


http://www.niftyadmin.cn/n/1999901.html

相关文章

noip欢乐赛10.24 分火腿

分火腿 题目描述: 小月言要过四岁生日了,她的妈妈为她准备了n根火腿,她想将这些火腿均分给m位小朋友,所以她可能需要切火腿。为了省事,小月言想切最少的刀数,使这n根火腿分成均等的m份。请问最少要切几刀&a…

mbr mysql_mbr是什么?

MBR即主引导记录,全称Main Boot Record,是位于磁盘最前边的一段引导(Loader)代码。它负责磁盘操作系统(DOS)对磁盘进行读写时分区合法性的判别、分区引导信息的定位,它由磁盘操作系统(DOS)在对硬盘进行初始化时产生的。通常,我们将…

(六)easyUI之对话框窗口

一、拥有HTML的对话框 <% page language"java" contentType"text/html; charsetUTF-8"pageEncoding"UTF-8"%><%String pathrequest.getContextPath(); %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN&q…

诸葛亮是刘备最器重的人才么

诸葛亮是刘备最器重的人才么 近来&#xff0c;对诸葛亮军事才能的评论比较多。有的认为诸葛亮军事才能不高&#xff0c;于演义和历史上对其的评价相差甚远&#xff1b;还有的则认为诸葛亮不愧为伟大的军事家。本文从另一个角度来分析一下诸葛亮的军事才能&#xff0c…

mysql concat 子查询_对MySQL中的子查询使用GROUP_CONCAT

我有一个MySQL查询&#xff0c;其中我想包括来自另一个表的ID列表。在网站上&#xff0c;人们可以添加某些项目&#xff0c;然后人们可以将这些项目添加到他们的收藏夹。我基本上想得到ID的人谁拥有该项目(这是一个有点简化&#xff0c;但这是它归结为)的列表。基本上&#xff…

Spring Cloud Edgware新特性之二:如何配置Zuul的Hystrix线程池

Spring Cloud是当前炙手可热的微服务开发框架。它的功能强大&#xff0c;组件丰富&#xff0c;设计优雅。目前Spring Cloud还在不断发展之中。 Spring Cloud即将发布Spring Cloud Edgware 版本。该版本解决了不少Bug&#xff0c;新增了不少新特性&#xff0c;本系列博客将为大家…

蜀中缘何无大将

蜀中缘何无大将 “蜀中无大将&#xff0c;廖化作先锋”&#xff0c;这句成语所揭示的原本是三国后期蜀汉人才奇缺的历史事实&#xff0c;后来则引伸为泛指因为没有杰出人才&#xff0c;平庸之辈也能侥幸成名&#xff0c;与“山中无老虎&#xff0c;猴子称霸王”意义相近。唐朝…

mysql自动增量备份_mysql自动增量备份的例子(本地备份与远程备份)

mysql自动增量备份的例子(本地备份与远程备份)&#xff0c;有需要的朋友可以参考下。1、本地备份编写自动备份脚本&#xff1a;vim /var/lib/mysql/autobak内容如下&#xff1a;复制代码 代码如下:cd /data/home/mysqlbakrq date %Y%m%d /usr/local/mysql/bin/mysqldump sqldb …