【发布时间】:2018-03-15 10:15:59
【问题描述】:
def my_decorator(some_function):
print("Something is happening before some_function() is called.")
some_function()
print("Something is happening after some_function() is called.")
def just_some_function():
print("Wheee!")
just_some_function = my_decorator(just_some_function)
just_some_function()
TypeError: 'NoneType' object is not callable
我真的不明白,为什么这不起作用?
根据我的理解,just_some_function 基本上应该是这样的:
just_some_function():
print("Something is happening before some_function() is called.")
print("Wheee!")
print("Something is happening after some_function() is called.")
但是原始函数需要一个包装函数才能工作,例如:
def my_decorator(some_function):
def wrapper():
print("Something is happening before some_function() is called.")
some_function()
print("Something is happening after some_function() is called.")
return wrapper
为什么?有人能解释一下它背后的逻辑吗?
【问题讨论】:
-
您确实意识到这一行
just_some_function = my_decorator(just_some_function)返回None。你的函数没有返回任何东西
标签: python python-3.x decorator python-decorators