装饰的怪异 [英] Strangeness with a decorator

查看:56
本文介绍了装饰的怪异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个装饰器,它将捕获异常并充分记录它们。

I want to make a decorator which will catch exceptions and adequately logged their.

def logger(foo):
    try:
        print foo()
    except Exception as e:
        print e

@logger
def d():
    return 2/2

if __name__ == '__main__':
    d()

我认为是正确的,但随后我运行了它,但出现了如下异常:

Thats right i think, but then I run it and I have an exception like this:

1

Traceback (most recent call last):

  File "log.py", line 14, in <module>

    d()

TypeError: 'NoneType' object is not callable

为什么解释器告诉我该函数具有None类型,但是调用它并显示答案?

Why interpreter tells me that the function has None type, but call it and print answer?

推荐答案

您的装饰器需要返回一个函数,但是它不返回任何东西,因此'TypeError:'NoneType'对象不可调用'。您可以通过以下方式实现它:

Your decorator needs to return a function, but it's not returning anything, hence the 'TypeError: 'NoneType' object is not callable'. You can implement it this way:

def logger(foo):
    def fn():
        try:
            print foo()
        except Exception as e:
            print e
    return fn

查看此问题以了解如何编写/使用装饰器。

Check out This question for a good example of how to write/use a decorator.

这篇关于装饰的怪异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆