首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python简单装饰问题

Python简单装饰问题
EN

Stack Overflow用户
提问于 2018-03-15 10:15:59
回答 1查看 65关注 0票数 0
代码语言:javascript
复制
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基本上应该变成这样:

代码语言:javascript
复制
just_some_function():
        print("Something is happening before some_function() is called.")  
        print("Wheee!")  
        print("Something is happening after some_function() is called.")  

但是,原始函数需要一个包装函数才能工作,例如:

代码语言:javascript
复制
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

为什么?谁能解释一下背后的逻辑吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-15 10:23:37

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

代码语言:javascript
复制
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‘对象不可调用

代码语言:javascript
复制
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__) ->的“包装器”。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49296780

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档