gpt4 book ai didi

python - __enter__ 和 __exit__ 如何在 Python 装饰器类中工作?

转载 作者:IT老高 更新时间:2023-10-28 20:51:58 25 4
gpt4 key购买 nike

我正在尝试创建一个装饰器类来计算函数被调用的次数,但我收到一条错误消息:

    "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 exit 函数的参数吗?任何提示或想法将不胜感激。

顺便说一句,我的代码行“print 'f count =',f.count”似乎是在输出内存地址而不是值,但这是一个完全不同的问题。

最佳答案

__exit__() 方法应该接受有关 with: block 中出现的异常的信息。见 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: block 之一中引发异常,它将被 __exit__() 捕获。

关于python - __enter__ 和 __exit__ 如何在 Python 装饰器类中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22417323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com