【问题标题】:Python simple decorator issuePython简单装饰器问题
【发布时间】: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


【解决方案1】:

装饰者应该创建“替换”原始功能的新功能。

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' object is not callable

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 = wrapper -> 它的工作。

您也可以检查。试试print(just_some_function.__name__) -> “包装器”。

【讨论】:

  • 嗯,很有趣。因此,当我说 just_some_function=my_decorator(just_some_function) 时,这意味着我说 just_some_function = 右侧的 RETURN,对吗?因为它没有明确返回某些东西,所以它会是 None?
  • 让我们再试一次。你说 just_some_function=my_decorator(just_some_function) 它的意思是 just_some_function = wrapper。
  • 因为 wrapper 被返回,而不是因为它是唯一的内部函数,对吗?
猜你喜欢
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 2017-09-20
  • 1970-01-01
  • 2011-01-10
  • 1970-01-01
  • 1970-01-01
  • 2016-10-05
相关资源
最近更新 更多