【问题标题】:decorator 'NoneType' object is not callable装饰器“NoneType”对象不可调用
【发布时间】:2018-08-17 08:34:10
【问题描述】:

我正在尝试编写一个简单的装饰器,将 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

我做错了什么?

【问题讨论】:

  • 我在任何地方都看不到 return 语句...
  • 我认为你应该从你的装饰者那里返回包装器
  • @our_decorator 是一种语法糖。这与test = our_decorator(test) 和调用test() 相同。由于您的装饰器返回NoneNone() 将导致TypeError: 'NoneType' object is not callable

标签: python python-decorators


【解决方案1】:

装饰器需要返回被装饰函数的包装器:

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 在 cmets 中正确指出的那样:在装饰器中返回函数的结果并没有什么坏处。虽然在这种特定情况下并不重要,但通常是您想要的。

【讨论】:

  • 另外它可能需要在包装器内返回调用func的结果。
猜你喜欢
  • 1970-01-01
  • 2022-01-03
  • 2020-08-19
  • 2013-01-10
  • 2021-11-22
  • 2019-03-17
  • 2020-09-22
  • 1970-01-01
  • 2019-11-18
相关资源
最近更新 更多