我正在尝试创建一个装饰器类来计算函数被调用的次数,但是我收到了一个错误信息,上面写着:
"TypeError: __exit__() takes exactly 1 argument (4 given)"
我真的不知道我是如何给它传递四个参数的。我的代码看起来像这样:
class fcount2(object):
__instances = {}
def __init__(self, f):
self.__f = f
self.__numcalls = 0
fcount2.__instances[f] = self
def __call__(self, *args, **kwargs):
self.__numcalls += 1
return self.__f(*args, **kwargs)
def __enter__(self):
return self
def __exit__(self):
return self
@staticmethod
def count(f):
return fcount2.__instances[self.__f].__numcalls
@fcount2
def f(n):
return n+2
for n in range(5):
print f(n)
print 'f count =',f.count
def foo(n):
return n*n
with fcount2(foo) as g:
print g(1)
print g(2)
print 'g count =',g.count
print 'f count =',f.count
with fcount2(f) as g:
print g(1)
print g(2)
print 'g count =',g.count
print 'f count =',f.count
with f:
print f(1)
print g(2)
print 'g count =',g.count
print 'f count =',f.count
我是否需要传递其他参数到 exit 函数中?或者不应该传递一些参数?如果您有任何提示或想法,请告诉我。
顺便说一下,我的代码行 "print 'f count =',f.count" 看起来输出的是内存地址而不是值,但这是完全不同的问题。