2024-09-22 16:29:07 发布
网友
我试图用python实现decorators,但在第14行出现了一个错误,即hello()
hello()
#The code- def maint(item1): def greet(): print("Good Morning") item1() print("Tanish") return greet() #decorator---- @maint def hello(): print("Hello") # hello=maint(hello) hello()
我做错了什么
return greet()
在decorator中,调用greet()并返回其结果。由于greet()没有显式返回,因此结果是None。这将有助于认识到decorator是以下内容的简写语法:
greet()
None
def hello(): pass hello = maint(hello)
注意hello是如何被重新分配给maint()返回的任何内容的。在您的情况下,hello被重新分配给None。因此调用hello()会导致错误
maint()
hello
要解决这个问题,只需return greet不带括号。装饰器总是返回一个函数。他们不应该调用该函数
return greet
在decorator中,调用
greet()
并返回其结果。由于greet()
没有显式返回,因此结果是None
。这将有助于认识到decorator是以下内容的简写语法:注意hello是如何被重新分配给
maint()
返回的任何内容的。在您的情况下,hello
被重新分配给None
。因此调用hello()
会导致错误要解决这个问题,只需
return greet
不带括号。装饰器总是返回一个函数。他们不应该调用该函数相关问题 更多 >
编程相关推荐