【发布时间】: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()相同。由于您的装饰器返回None,None()将导致TypeError: 'NoneType' object is not callable