首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >__enter__和__exit__在Python装饰器类中是如何工作的?

__enter__和__exit__在Python装饰器类中是如何工作的?
EN

Stack Overflow用户
提问于 2014-03-15 07:02:46
回答 2查看 18.8K关注 0票数 37

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

    "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“似乎输出的是内存地址而不是值,但这是一个完全不同的问题。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 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__()中被捕获。

票数 66
EN

Stack Overflow用户

发布于 2021-04-18 23:41:32

你得到这个错误的原因是因为__exit__()self一起接受了3个参数。它们是:

  1. exception_type
  2. exception_value
  3. traceback

您可以通过两种方式定义__exit__()方法:

def __exit__(self, exception_type, exception_value, traceback):

def __exit__(self, *args, **kwargs):

with语句支持由使用__enter__() & __exit__()方法对实现的上下文管理器定义的运行时上下文的概念。有关详细信息,请访问此link

__enter__()方法将进入运行时上下文,并返回此对象或与运行时上下文相关的另一个对象。

__exit__()方法将退出运行时上下文,并返回一个布尔标志,指示是否应抑制发生的任何异常。这些参数的值包含有关抛出的异常的信息。如果值等于None表示没有引发异常,则为

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22417323

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档