python高级编程装饰器_Python装饰器

def my_decorator(function):

def _my_decorator(*args, **kw):

#在调用实际函数之前做些填充工作

res = function(*args, **kw)

#做完某些填充工作之后

return res

#返回子函数

return _my_decorator

当装饰器需要参数时,必须使用第二级封装。

def my_decorator(arg1, arg2):

def _my_decorator(function):

def __my_decorator(*args, **kw):

res = function()

return res

return __my_decorator

return _my_decorator

引用

因为装饰器在模块第一次被读取时由解释程序装入,所以它们的使用必须受限于总体上可以应用的封装器。如果装饰器与方法的类或所增强的函数签名绑定,它应该被重构为常规的可调用对象,从而避免复杂性。在任何情况下,当装饰器处理API时,一个好的方法是将它们聚集在一个易于维护的模块中。

参数检查:

def check_param_isvalid():

def check(method):

def check_param(*args,**kwargs):

for a in args:

assert isinstance(a, int),"arg %r does not match %s" % (a,int)

assert a > 100000,"arg %r must gt 100000" % a

return method(*args, **kwargs)

return check_param

return check

@check_param_isvalid()

def foo(*args):

print args

foo(200000,500000)

缓存:

import time

import hashlib

import pickle

cache = {}

def is_obsolete(entry, duration):

return time.time() - entry['time'] > duration

def computer_key(function, args, kw):

key = pickle.dumps((function.func_name, args, kw))

return hashlib.sha1(key).hexdigest()

def memoize(duration=30):

def _memoize(function):

def __memoize(*args, **kw):

key = computer_key(function, args, kw)

if key in cache and not is_obsolete(cache[key], duration):

print 'wo got a winner'

return cache[key]['value']

result = function(*args, **kw)

cache[key] = {'value':result,'time':time.time()}

return result

return __memoize

return _memoize

@memoize()

def very_complex_stuff(a,b):

return a + b

print very_complex_stuff(2,2)

代理:

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 won't 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 'use tons of butter!'

these_are = MySecrets()

user = tarek

these_are.waffle_recipe()

user = bill

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():

print 'haha'

thread_safe()

补充:http://2057.iteye.com/blog/1838398

参考资料:

Python高级编程

分享到:

2013-10-15 22:59

浏览 1214

评论

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/442023.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【HihoCoder - 1269】 优化延迟 (优先队列+二分优化)

题干&#xff1a; 小Ho编写了一个处理数据包的程序。程序的输入是一个包含N个数据包的序列。每个数据包根据其重要程度不同&#xff0c;具有不同的"延迟惩罚值"。序列中的第i个数据包的"延迟惩罚值"是Pi。如果N个数据包按照<Pi1, Pi2, ... PiN>的顺…

带有风的诗词_带有风的诗句

带有风的诗句1、古道西风瘦马&#xff0c;夕阳西下&#xff0c;断肠人在天涯。——马致远《天净沙秋思》2、欲乘风归去&#xff0c;又恐琼楼玉宇。——苏轼《水调歌头明月几时有》3、道通天地有形外&#xff0c;思入风云变态中。——程颢《秋日》4、津亭杨柳碧毵毵&#xff0c;…

【ZOJ - 3210】A Stack or A Queue? (模拟)

题干&#xff1a; Do you know stack and queue? Theyre both important data structures. A stack is a "first in last out" (FILO) data structure and a queue is a "first in first out" (FIFO) one. Here comes the problem: given the order of …

ehchache验证缓存过期的api_Ehcache缓存配置

Cache的配置很灵活&#xff0c;官方提供的Cache配置方式有好几种。你可以通过声明配置、在xml中配置、在程序里配置或者调用构造方法时传入不同的参数。你可以将Cache的配置从代码中剥离出来&#xff0c;也可以在使用运行时配置&#xff0c;所谓的运行时配置无非也就是在代码中…

*【POJ - 3061】 Subsequence (尺取或二分)

题干&#xff1a; A sequence of N positive integers (10 < N < 100 000), each of them less than or equal 10000, and a positive integer S (S < 100 000 000) are given. Write a program to find the minimal length of the subsequence of consecutive eleme…

alert 回调_JavaScript中到底什么时候回调函数Callback

什么是回调函数Callback简单的理解&#xff1a;回调函数是在另一个函数执行完毕后执行的函数 - 因此名称为call back。复杂的理解&#xff1a;在JavaScript中&#xff0c;函数是对象。因此&#xff0c;函数可以将函数作为参数&#xff0c;并且可以由其他函数返回。执行此操作的…

【CF#148B】Escape(模拟)

题干&#xff1a; The princess is going to escape the dragons cave, and she needs to plan it carefully. The princess runs at vp miles per hour, and the dragon flies at vd miles per hour. The dragon will discover the escape after t hours and will chase the…

mysql sql语句分页查询_如何用sql语句 实现分页查询?

我制作了一个数据库其中一张表createtablenews(news_idintprimarykeyidentity(1,1),news_titlevarchar(50)notnull,news_authorvarchar(20),news_summaryvarchar(50),news_contenttext...我制作了一个数据库其中一张表create table news(news_id int primary key identity(1,1)…

*【HDU - 1042 】 N! (大数乘法)

题干&#xff1a; Given an integer N(0 ≤ N ≤ 10000), your task is to calculate N! Input One N in one line, process to the end of file. Output For each N, output N! in one line. Sample Input 1 2 3 Sample Output 1 2 6 解题报告&#xff1a; 大数运…

【bzoj 1754】【POJ - 2389 】Bull Math (高精度运算)

题干&#xff1a; Bulls are so much better at math than the cows. They can multiply huge integers together and get perfectly precise answers ... or so they say. Farmer John wonders if their answers are correct. Help him check the bulls answers. Read in two…

mysql居左查询abcd_数据库--查询语句

查询语句mysql中要学习的知识&#xff1a;多表关系&#xff0c;查询语句&#xff0c;索引添加数据补充将一个查询结果插入到另一张表中create table student(name char(10), gender int);insert into student values(nalituo, 1);insert into student values(sasigi, 0);create…

druid mysql配置详解_druid 参数配置详解

spring.datasource.typecom.alibaba.druid.pool.DruidDataSource#驱动配置信息spring.datasource.driver-class-namecom.mysql.jdbc.Driver#基本连接信息spring.datasource.username rootspring.datasource.password rootspring.datasource.urljdbc:mysql://192.168.153.23:3…

【POJ - 2376】Cleaning Shifts (贪心)

题干&#xff1a; Farmer John is assigning some of his N (1 < N < 25,000) cows to do some cleaning chores around the barn. He always wants to have one cow working on cleaning things up and has divided the day into T shifts (1 < T < 1,000,000), …

mysql sql 片段_MySQL代码片段

1.[代码][SQL]代码--导出为xml文件mysql -X -uroot -proot -e "use testa;select * from test_tb;" > /opt/test.xml--导出为csv文件--fields terminated 分割记录中每个字段的字符--optionally enclosed 包围每个字段的字符--lines terminated 每行结束的字符--P…

【HDU - 4990】 Reading comprehension (构造+矩阵快速幂)

题干&#xff1a; Read the program below carefully then answer the question. #pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include<iostream> #include <cstring> #include <cmath> #include &…

finereport文本框如何实现多值查询_如何实现参数级联查询

参数级联查询是查询控件之间的一种互动方式&#xff0c;比如在某个下拉框选定选项后&#xff0c;另一个下拉框里的选项范围会随之变化。润乾报表提供了多种编辑风格&#xff0c;每种编辑风格都有丰富的属性&#xff0c;以此为基础实现参数级联查询也很简单。下面就通过一个例子…

【HDU - 5015 】233 Matrix (矩阵快速幂)

题干&#xff1a; In our daily life we often use 233 to express our feelings. Actually, we may say 2333, 23333, or 233333 ... in the same meaning. And here is the question: Suppose we have a matrix called 233 matrix. In the first line, it would be 233, 233…

【HDU - 2899】 Strange fuction(二分或三分,求导)

题干&#xff1a; Now, here is a fuction: F(x) 6 * x^78*x^67*x^35*x^2-y*x (0 < x <100) Can you find the minimum value when x is between 0 and 100. Input The first line of the input contains an integer T(1<T<100) which means the number of…

php mysql html标签_HTML标签格式化PHP和MySQL

我有这个MySQL语句Select type.type, color.color, ShotName, Item.name, Item.Item_idFrom typeInner Join ItemOn type.type_id Item.type_idInner Join colorOn color.color_id Item.color_idWhere Item.state0 And Item.offline 0Group By color.color, Item.name, type.o…

【CF#706B】 Interesting drink (二分)

题干&#xff1a; 瓦西里喜欢在努力工作后休息&#xff0c;所以你可能经常在附近的一些酒吧见到他。他喜欢 "Beecola"&#xff0c;可以从 n 个不同的商店买到。在第 i 个商店的价格为 xi 元。 瓦西里计划购买他最喜欢的饮料 q 次。在第 i 天他能花 mi 元。他想知道每…