与块一起使用时出现Python未定义错误

与块一起使用时出现Python未定义错误,python,Python,这是一个装饰师。其思想是在使用“with”块时保留单独的计数 如果我这样做: 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

这是一个装饰师。其思想是在使用“with”块时保留单独的计数

如果我这样做:

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
我得到这个错误: TypeError:“非类型”对象不可调用

我试着用块打印出里面的g类型,当然类型是无

知道为什么g没有被分配到fcount(foo)吗

这确实有效:

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

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

您忘了从
返回对象\u\u enter\u()

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