我需要知道为什么这个代码的输出是sayhello()only?

def myDecorator(func):  # Decorator

    def nestedfunc():  # Any Name Its Just For Decoration
        print("Before")  # Message From Decorator

        func()  # Execute Function

        print("After")  # Message From Decorator

    return nestedfunc  # Return All Data


def sayHello():
    print("Hello from sayHello function")


myDecorator(sayHello())

推荐答案

myDecorator(sayHello())次调用sayHello()返回Nonethen次调用myDecorator(None)返回nestedfunc,实际上没有被调用.

使用以下方法修饰函数并调用它:

def myDecorator(func):
    def nestedfunc():
        print("Before")
        func()
        print("After")
    return nestedfunc

@myDecorator  # correct decorator syntax
def sayHello():
    print("Hello from sayHello function")

sayHello()

输出:

Before
Hello from sayHello function
After

decorator(@)语法等价于以下内容:

def myDecorator(func):
    def nestedfunc():
        print("Before")
        func()
        print("After")
    return nestedfunc

def sayHello():
    print("Hello from sayHello function")

# Pass sayHello as the func parameter to MyDecorator
# and return nestedfunc.  Reassign to sayHello.
sayHello = myDecorator(sayHello)

sayHello()  # now really calling nestedfunc.

Python相关问答推荐

根据给定日期的状态过滤查询集

Python中使用时区感知日期时间对象进行时间算术的Incredit

Pandas 在最近的日期合并,考虑到破产

如何将双框框列中的成对变成两个新列

将数据框架与导入的Excel文件一起使用

如果值不存在,列表理解返回列表

用Python解密Java加密文件

无法使用DBFS File API路径附加到CSV In Datricks(OSError Errno 95操作不支持)

如果值发生变化,则列上的极性累积和

如何禁用FastAPI应用程序的Swagger UI autodoc中的application/json?

为什么numpy. vectorize调用vectorized函数的次数比vector中的元素要多?

判断solve_ivp中的事件

Python避免mypy在相互引用中从另一个类重定义类时失败

Gunicorn无法启动Flask应用,因为无法将应用解析为属性名或函数调用.'"'' "

为什么Python内存中的列表大小与文档不匹配?

30个非DATETIME天内的累计金额

Matplotlib中的曲线箭头样式

大型稀疏CSR二进制矩阵乘法结果中的错误

如何在Polars中创建条件增量列?

用LAKEF划分实木地板AWS Wrangler