2012-03-09 58 views
2
class fcount(object): 
    def __init__(self, func): 
      self.func = func 
      self.count = 0 
      self.context_count = 0 
    def __enter__(self): 
      self.context_count = 0 
    def __call__(self, *args): 
      self.count += 1 
      self.context_count += 1 
      return self.func(*args) 
    def __exit__(self, exctype, value, tb): 
      return False 

這是一個裝飾器。這個想法是在使用'with'塊時保持一個單獨的計數。使用塊時Python未定義錯誤

如果我這樣做:

@fcount 
def f(n): 
    return n+2 

with fcount(foo) as g: 
    print g(1) 

我得到這個錯誤: 類型錯誤:「NoneType」對象不是可調用

我試着打印出G的類型內,隨着塊,和當然類型是None。

任何想法爲什麼g沒有被分配給fcount(foo)?

這並不工作:

g = fcount(foo) 
with g: 
    g(1) 

回答

2

你忘了從__enter__()返回對象。