装饰器类装饰类方法

时间:2015-02-11 14:52:41

标签: python python-2.7 python-decorators

我有一个我作为班级实施的装饰师:

class Cached(object):
    def __init__(self, func):
        self.cache = None
        self.func = func

     def __call__(self, *args, **kwargs):
         if self.cache is None or (time.time() - self.cache[0] >= 1000):
             res = self.f(*args, **kwargs)
             self.cache = (time.time(), res)
         else:
             res = self.cache[1]
         return res

我想使用这个装饰器来装饰类的方法,例如:

class Foo(object):
    def __init__(self, x):
        self.x = x

    @cached
    def bar(self, y):
        return self.x + y

目前,

f = Foo(10)
f.bar(11)

抛出TypeError: foo() takes exactly 2 arguments (1 given)f.bar(f, 11)有效,但在卫生工作者罢工期间,代码气味相当于纽约市的夏季。我错过了什么?

ETA:最初,我试图将Cached实现为一个函数:

def cached(cache):
    def w1(func):
        def w2(*args, **kwargs):
            # same 
        return w2
    return w1

但是在我定义之前我一直在使用cache时遇到奇怪的范围错误,这些错误会切换到固定的装饰器类。

1 个答案:

答案 0 :(得分:1)

您需要将它添加到装饰器类:

def __get__(self, obj, objtype):
     """support instance methods"""
     from functools import partial
     return partial(self.__call__, obj)