2015-02-11 295 views
0

我已经得到了我实现了作为一个一流的装饰:装饰类装饰类方法

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:本来,我是想实现缓存作为一个函数:

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

,但我一直得到约cache奇怪的作用域的错误使用它的定义之前,它切换到固定一个装饰类。

回答

1

您需要添加到您的装饰类:

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