2015-02-11 300 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)