我正在尝试创建一个装饰器类来计算函数被调用的次数,但是我得到了一条错误消息,说:
"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
有没有其他一些我应该(或者不应该)传递给def 出口函数的参数?任何建议或想法都将不胜感激。
顺便说一句,我的代码行"print 'f count =',f.count“似乎输出的是内存地址而不是值,但这是一个完全不同的问题。
发布于 2014-03-15 07:15:31
__exit__()
方法应该接受有关出现在with:
块中的异常的信息。参见here。
对您的代码进行以下修改:
def __exit__(self, exc_type, exc_value, tb):
if exc_type is not None:
traceback.print_exception(exc_type, exc_value, tb)
# return False # uncomment to pass exception through
return True
然后,您可以尝试在某个with:
块中引发异常,它将在__exit__()
中被捕获。
发布于 2021-04-18 23:41:32
你得到这个错误的原因是因为__exit__()
和self
一起接受了3个参数。它们是:
您可以通过两种方式定义__exit__()
方法:
def __exit__(self, exception_type, exception_value, traceback):
或
def __exit__(self, *args, **kwargs):
with
语句支持由使用__enter__()
& __exit__()
方法对实现的上下文管理器定义的运行时上下文的概念。有关详细信息,请访问此link。
__enter__()
方法将进入运行时上下文,并返回此对象或与运行时上下文相关的另一个对象。
__exit__()
方法将退出运行时上下文,并返回一个布尔标志,指示是否应抑制发生的任何异常。这些参数的值包含有关抛出的异常的信息。如果值等于None表示没有引发异常,则为。
https://stackoverflow.com/questions/22417323
复制相似问题