首页 > 解决方案 > 装饰器中的这个函数如何在 Python 中工作?

问题描述

def title_decorator(print_name_function):
#in addition to printing name it will print a title
    def wrapper():
        #it will wrap print_my_name with some functionality
        print("Professor:")
        print_name_function() #<----- QUESTION HERE
        #wrapper will print out professor and then call print_name_function
    return wrapper

def print_my_name():
    print("Joseph")

def print_mike():
    print("Mike")

decorated_function = title_decorator(print_mike)
#calling decorator function, passing in print_my_name

decorated_function
decorated_function()

def wrapper()we have下print_name_function(),这是如何工作的,为什么我们将()这里包括在内?

我看到我们正在print_name_function进入title_decorator

但我不太明白它是如何被包含在其中的,以及包含在后面def wrapper()意味着什么()print_name_function()

标签: pythonfunctiondecorator

解决方案


把装饰器想象成一个返回另一个函数的函数。您要做的是在不更改其实现的情况下向函数添加行为。

在实践中,装饰器具有以下行为。

def title_decorator(print_name_function):

    # now your decorator have a local variable (print_name_function) 
    # in that function scope that variable is a reference to another 
    # function

    def wrapper():
        # now you write a function that do something

        print("Professor:")
        print_name_function() # here you function is calling a scope 
                              # variable that by the way is another 
                              # function. See that the scope of this 
                              # variable is *title_decorator*


    # now instead to return your argument function you return another
    # with some other behavior
    return wrapper

OBS:当包装器调用函数时,这是对对象的引用。记住这一点


推荐阅读