装饰器 TypeError: 'NoneType' object is not callable
def simple_decorator(f):
print('in in in')
f()
print('out out out')
@simple_decorator
def test():
print('this just a test')
test()
会报错,解决方案:最后的test()改为test即可,因为simple_decorator没有return。
当()被附加在方法或者类后面时,表示调用,当对象不具备调用性的时候,就会报错:‘某个类型’ object is not callable。
当一个方法被调用后,是否能被再次执行,取决于它是否会return一个对象,并且该对象可以被调用。
@simple_decorator装饰test,可理解为test = simple_decorator(test),执行test(),首先,执行simple_decorator(test),由于simple_decorator没有返回值,此时test()等价于none(),所以simple_decorator(test)()没有对象可以调用,就会报错TypeError: ‘NoneType’ object is not callable。
因此,解决方案也可以是:
1.simple_decorator最后加上return f,此时执行结果为:
in in in
this just a test
out out out
print(test,test())会得到:<function test at 0x0000016A3966D670>,
this just a test, None
2.最后加上return f (),此时test运行后结果为,相当于用装饰器装饰test后再次单独调用test:
in in in
this just a test
out out out
this just a test
print(test)会得到:none
而test()会报错:TypeError: ‘NoneType’ object is not callable
此时,若在test函数内加return 1,则print(test)则会得到1
上一篇: 路由器 telnet配置
推荐阅读
-
装饰器 TypeError: 'NoneType' object is not callable
-
U-Net运行报错merge6 = merge([drop4,up6], mode = 'concat'...) TypeError: 'module' object is not callable
-
TypeError: the JSON object must be str, bytes or bytearray, not NoneType
-
面向对象编程Object-Oriented和装饰器decorator
-
解决Flask错误“TypeError: 'bool' object is not callable”
-
python报错:TypeError: ‘NoneType‘ object is not subscriptable
-
成功解决TypeError: ‘tuple‘ object is not callable
-
TypeError系列之:TypeError: 'tuple' object is not callable.
-
Django关于TypeError: 'tuple' object is not callable解决方式
-
TypeError: ‘tuple‘ object is not callable