Python简单装饰器问题

时间:2018-03-15 10:16:00

标签: python python-3.x decorator python-decorators

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

为什么呢?有人可以解释它背后的逻辑吗?

1 个答案:

答案 0 :(得分:2)

装饰者应该创造新的功能"替换"原始功能。

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.")

这个"装饰" return None - > just_some_function =无 - > 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 = wrapper - >它的工作。

您也可以查看。试试print(just_some_function.__name__) - > "包装"