装饰器“ NoneType”对象不可调用

时间:2018-08-17 08:34:10

标签: python python-decorators

我正在尝试编写一个简单的装饰器,将try / except添加到打印错误的任何函数中。

import random

def our_decorator(func):
    def function_wrapper(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except Exception as e:
                print(e)

@our_decorator
def test():    
    for a in range(100):
        if a - random.randint(0,1) == 0:
            print('success count: {}'.format(a))
            pass
        else:
            print('error count {}'.format(a))
            'a' + 1

我不断收到错误消息:

TypeError: 'NoneType' object is not callable

我在做什么错了?

1 个答案:

答案 0 :(得分:3)

装饰器需要返回围绕装饰功能的包装器:

import random

def our_decorator(func):
    def function_wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            print(e)
    return function_wrapper

@our_decorator
def test():    
    for a in range(100):
        if a - random.randint(0,1) == 0:
            print('success count: {}'.format(a))
            pass
        else:
            print('error count {}'.format(a))
            'a' + 1

正如丹尼尔·罗斯曼(Daniel Roseman)在评论中正确指出的那样:在装饰器中返回该函数的结果不会有任何伤害。尽管在这种特定情况下无关紧要,但这通常是您想要的。