这个问题已经在这里有了答案: > How can I decorate an instance method with a decorator class? 3个
我正在尝试使用装饰器进行记忆,该装饰器是一个类而不是一个函数,但出现错误
TypeError: seqLength() takes exactly 2 arguments (1 given)
我猜想这与类有关,但是不确定那里出了什么问题.
编码:
import sys
class memoize(object):
'''memoize decorator'''
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
try:
return self.cache[args]
except KeyError:
value = self.func(self, *args)
self.cache[args] = value
return value
class collatz(object):
def __init__(self, n):
self.max = 1
self.n = n
@memoize
def seqLength(self, n):
if n>1:
if n%2 == 0:
return 1+self.seqLength(n/2)
else:
return 1+self.seqLength(3*n+1)
else:
return 1
def maxLength(self):
for n in xrange(1, self.n):
l = self.seqLength(n)
if l > self.max:
self.max = n
return self.max
n = int(sys.argv[1])
c = collatz(n)
print c.maxLength()
解决方法:
装饰器只是foo = decorator(foo)的语法糖,因此在这种情况下,您最终要使seqLength的自身成为备忘录而不是collatz.您需要使用描述符.该代码对我有用:
class memoize(object):
'''memoize descriptor'''
def __init__(self, func):
self.func = func
def __get__(self, obj, type=None):
return self.memoize_inst(obj, self.func)
class memoize_inst(object):
def __init__(self, inst, fget):
self.inst = inst
self.fget = fget
self.cache = {}
def __call__(self, *args):
# if cache hit, done
if args in self.cache:
return self.cache[args]
# otherwise populate cache and return
self.cache[args] = self.fget(self.inst, *args)
return self.cache[args]
有关描述符的更多信息:
http://docs.python.org/howto/descriptor.html#descriptor-example