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为什么?谁能解释一下背后的逻辑吗?
发布于 2018-03-15 10:23:37
装饰师应该创建“替换”原有功能的新功能。
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.")这个“装饰器”返回None -> just_some_function = None -> TypeError:'NoneType‘对象不可调用
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 =包装器-> --它正在工作。
你也可以检查。试试print(just_some_function.__name__) ->的“包装器”。
https://stackoverflow.com/questions/49296780
复制相似问题