首先是“智能功能”的概念:
>>> def f(x,check={}):
if x not in check:
print 'call f'
check[x]=2*x
return check[x]
>>> f(2)
call f
4
>>> f(2)
4
>>> f(3)
call f
6
>>> 这意味着,如果给出相同的参数,它只计算once.when,而不是先调用,它直接返回值。
我非常重视这种functions.Because,您不必定义varible来存储值,而是保存计算源。
但是这个函数太简单了,当我想要定义另一个智能函数g时,我必须重复如下:
>>> def g(x,check={}):
if x not in check:
print 'call g'
check[x]=x**2
return check[x]因此,我的问题来了,如何定义一个装潢师“懒惰”,它的工作方式如下:
@lazy
def func(a,b,*nkw,**kw):
print 'call func'
print a,b
for k in nkw:
print k
for (k,v) in kw.items():
print k,v
#do something with a,b,*kw,**nkw to get the result
result=a+b+sum(nkw)+sum(kw.values())
return result
print '--------1st call--------'
print func(1,2,3,4,5,x=6,y=7)
print '--------2nd call--------'
print func(1,2,3,4,5,x=6,y=7)结果:
>>>
--------1st call--------
call func
1 2
3
4
5
y 7
x 6
28
--------2nd call--------
28注意,如果没有*kw或**nkw,即:func(1,2)也需要预先工作smart.thanks!
发布于 2013-10-20 17:29:29
来自https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
class memoized(object):
'''Decorator. Caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned
(not reevaluated).
'''
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
if not isinstance(args, collections.Hashable):
# uncacheable. a list, for instance.
# better to not cache than blow up.
return self.func(*args)
if args in self.cache:
return self.cache[args]
else:
value = self.func(*args)
self.cache[args] = value
return value
def __repr__(self):
'''Return the function's docstring.'''
return self.func.__doc__
def __get__(self, obj, objtype):
'''Support instance methods.'''
return functools.partial(self.__call__, obj)发布于 2013-10-20 17:50:50
在nooodl的帮助下,我从页面https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize中找到了我想要的答案。
在此与大家分享:
import collections,functools
def memoize(obj):
cache = obj.cache = {}
@functools.wraps(obj)
def memoizer(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = obj(*args, **kwargs)
return cache[key]
return memoizer
@memoize
def func(a,b,*nkw,**kw):
print 'call func'
print a,b
for k in nkw:
print k
for (k,v) in kw.items():
print k,v
#do something with a,b,*kw,**nkw to get the result
result=a+b+sum(nkw)+sum(kw.values())
return result
print '--------1st call--------'
print func(1,2,3,4,5,x=6,y=7)
print '--------2nd call--------'
print func(1,2,3,4,5,x=6,y=7)https://stackoverflow.com/questions/19480438
复制相似问题