This question already has answers here:
How can I decorate an instance method with a decorator class?
(3个答案)
去年关门了。
我试图记住使用decorator时,decorator是一个类,而不是一个函数,但是我得到了一个错误
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()

最佳答案

decorator只是foo = decorator(foo)的语法糖,因此在本例中,您将使selfseqLength变成memoize,而不是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

关于python - python中的类装饰器装饰方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8856164/

10-10 16:24