相反,你可以使用一個描述符(財產等),一個裝飾的:
class Memoize(object):
def __init__(self, name, func):
self.name = name # name of the memo attribute
self.func = func # the function that is executed when there is no memo
def __get__(self, obj, typ=None):
if obj:
try:
return getattr(obj, self.name)
except:
setattr(obj, self.name, self.func())
return getattr(obj, self.name)
else:
return self
然後設置描述:
class Fun(object):
meth = Memoize('x', lambda: print('in') or 10)
然後交互式測試:
>>> f = Fun()
>>> f.meth # function is executed
'in'
10
>>> f.x
10
>>> f.meth # function is not executed
10
如果你真的想要一個裝飾者:
def memoize(func):
def inner(self):
try:
return self.memo_slow_method # hardcoded memo attribute name
except:
self.memo_slow_method = func(self) # execute the method body
return self.memo_slow_method
return inner
class Fun(object):
@memoize
def meth(self):
print('in')
return 100
>>> f = Fun()
>>> f.meth()
'in'
100
>>> f.meth()
100
>>> f.memo_slow_method
100
會有什麼some_slow_function回來嗎?方法還是值?請問slow_method函數返回嗎? –
有一個[memoization修飾器的配方](https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize)。由於Python 3.2,[類似](https://docs.python.org/3/library/functools.html#functools.lru_cache)包含在標準庫中。 – mkrieger1