Python装饰器

编写自定义装饰器有许多方法,但最简单和最容易理解的方法是编写一个函数,返回封装原始函数调用的一个子函数。

通用的模式如下。

def my_decorator(function):
def _my_decorator(*args, **kw):
#在调用实际函数之前做些填充工作
res = function(*args, **kw)
#做完某些填充工作之后
return res
#返回子函数
return _my_decorator

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

def my_decorator(arg1, arg2):
def _my_decorator(function):
def __my_decorator(*args, **kw):
res = function()
return res
return __my_decorator
return _my_decorator

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

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)

[b]缓存:[/b]

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)


[b]代理:[/b]

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

[b]上下文提供者[/b]:

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


补充:[url]http://2057.iteye.com/blog/1838398[/url]
参考资料:
Python高级编程
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值