代码之家  ›  专栏  ›  技术社区  ›  عبود عيد

调用decorator返回原始函数的输出

  •  1
  • عبود عيد  · 技术社区  · 3 月前

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

    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())
    
    2 回复  |  直到 3 月前
        1
  •  2
  •   Mark Tolonen    3 月前

    myDecorator(sayHello()) 电话 sayHello() 返回 None 然后 电话 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.
    
        2
  •  1
  •   Andrej Kesely    3 月前

    具有 myDecorator(sayHello()) 您首先运行 sayHello() 打印的函数 "Hello from sayHello function" 并返回 None .

    那么这个 没有一个 传递给 myDecorator() 返回 nestedfunc 。您不运行此函数。如果你运行这个函数,你会得到一个错误。