2012-03-09 88 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__()返回对象。

相关问题