python装潢器就是用于拓展本来函数功效的一种特别函数,这个函数的特别的地方在于它的返回值也是一个函数,他的作用就是在不改原函数的代码条件下增长函数的功效。
1 异常处置:
try-exception是python捕获异常的常常使用方法,但在代码频繁的应用,采取装潢器对try-catch进行了封装。异常处置应用装潢器.
def get_decorator(errors=(Exception, ), default_value=""):
def decorator(func):
def new_func(*args, **kwargs):
try:
return func(*args, **kwargs)
except errors, e:
print "Got error! ", repr(e)
return default_value
return new_func
return decorator
try_except = get_decorator(default_value="default")
a = {}
@try_except
def example1(a):
return a["b"]
@try_except
def example2(a):
return doesnt_exist()
print example1(a)
print example2(a)
#Got error! KeyError("b",)
#default
#Got error! NameError("global name "doesnt_exist" is not #defined",)
#default
2 缓存
缓存装潢器和参数检讨装潢器很像,但是更关注那些内部状况不会影响输出的函数。对这样的函数,其每组参数都可以关联到一个奇特的成果。这类作风的编程是函数式编程的特点(函数编程请查看:https://en.wikipedia.org/wiki/Functional_programming),当输入值的聚集是有限的时可以应用。
因此,缓存装潢器能够将输出成果和发生这个成果所须要的输入参数绑定起来,这样在随后的雷同调用中便可以够直接返回成果。这类行动叫做记忆(memoizing,https://en.wikipedia.org/wiki/Memoizing),并且应用装潢器来实现是很简略的:
import time
import hashlib
import pickle
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 memoize(duration=10):
def _memoize(function):
def __memoize(*args, **kw):
key = compute_key(function, args, kw)
# do we have it already ?
if (key in cache and not is_obsolete(cache[key], duration)):
print("we got a winner")
return cache[key]["value"]
# computing
result = function(*args, **kw)
# storing the result
cache[key] = {
"value": result,
"time": time.time()
}
return result
return __memoize
return _memoize
下面是应用该装潢器的一个例子:
@memoize()
def very_very_very_complex_stuff(a, b):
# if your computer gets too hot on this calculation
# consider stopping it
return a + b
very_very_very_complex_stuff(2, 2)
4
very_very_very_complex_stuff(2, 2)
we got a winner
@memoize(1) # invalidates the cache after 1 second
def very_very_very_complex_stuff(a, b):
return a + b
very_very_very_complex_stuff(2, 2)
4
very_very_very_complex_stuff(2, 2)
we got a winner
4
cache
{"c2727f43c6e39b3694649ee0883234cf": {"value": 4, "time": 1199734132.7102251)}
time.sleep(2)
very_very_very_complex_stuff(2, 2)
4
缓存盘算代价‘昂贵’的函数,能够明显地晋升运用程序的性状,但是应用时要当心。缓存的值也能够被绑定到函数本身,来管理其作用域,性命周期,而不是寄存到一个集中的字典中。但是,更高效的缓存装潢器应当应用以高等缓存算法为基本的特别的缓存库。
python装潢器就是用于拓展本来函数功效的一种特别函数,这个函数的特别的地方在于它的返回