Как эта функция внутри декоратора работает в Python? - PullRequest
0 голосов
/ 01 апреля 2020
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() у нас есть print_name_function(), как это работает и почему мы включили сюда ()?

Я вижу, что мы переходим в print_name_function в title_decorator

Но я не совсем понимаю, как это было включено в def wrapper() и что означает включать () позади print_name_function()

Ответы [ 2 ]

1 голос
/ 01 апреля 2020

Думайте в декораторе как о функции, которая возвращает другую функцию. То, что вы хотите сделать, это добавить поведение к функции без изменения его реализации.

На практике этот декоратор имеет следующее поведение.

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: Когда wrapper вызывает функцию, это ссылка на объект. Имейте это в виду

0 голосов
/ 01 апреля 2020

Функция Simply Decorator используется для улучшения функциональности функции. Прочитайте комментарии моего кода, надеюсь, вы понимаете это.

def title_decorator(print_name_function):   # this function take one function as argument
    def wrapper(): # Here is Rapper function
        print("Professor:")
        print_name_function() #(<----- QUESTION HERE) Answer-----> We are calling the same function because without calling
                                    # doesn't work, basically the function we passed in title_decorator() calls print_name_function()
                                    # inside wrapper function,
        #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)    # Here you calling your function and give print_mike() function as an argument
                        # store it's returning value in variable named as decorated_function, so first time your decorator returns
                        # called wrapper() function
decorated_function()   # and then your variable become decorated_function is working as a function that's why you calling this```


...