Python简单修饰符issu

2024-04-16 11:46:04 发布

您现在位置:Python中文网/ 问答频道 /正文

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():
        print("Something is happening before some_function() is called.")  
        print("Wheee!")  
        print("Something is happening after some_function() is called.")  

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

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

为什么?有人能解释一下背后的逻辑吗?你知道吗


Tags: 函数ismydeffunctiondecoratorsomesomething
1条回答
网友
1楼 · 发布于 2024-04-16 11:46:04

修饰符应该创建“替换”原有函数的新函数。你知道吗

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

此“decorator”返回None->;just \u some \u 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

这个“decorator”返回包装器->;只是一些函数=包装器->;它的工作。你知道吗

你也可以查一下。试试print(just_some_function.__name__)->;“包装器”。你知道吗

相关问题 更多 >