在Python中,装饰器中的这个函数是如何工作的?
在def包装器下,我们有print_name_函数,它是如何工作的,为什么我们在这里包括它 我看到我们正在将print\u name\u函数传递给title\u decorator在Python中,装饰器中的这个函数是如何工作的?,python,function,decorator,Python,Function,Decorator,在def包装器下,我们有print_name_函数,它是如何工作的,为什么我们在这里包括它 我看到我们正在将print\u name\u函数传递给title\u decorator 但我真的不明白它是如何包含在def包装器中的,以及在print_name_函数后面包含它意味着什么。您要做的是在不更改其实现的情况下向函数添加行为 实际上,装饰师有以下行为 def title_decororPrint_name_函数: 现在,您的装饰器有一个局部变量print\u name\u函数 在该函数范围内,
但我真的不明白它是如何包含在def包装器中的,以及在print_name_函数后面包含它意味着什么。您要做的是在不更改其实现的情况下向函数添加行为 实际上,装饰师有以下行为 def title_decororPrint_name_函数: 现在,您的装饰器有一个局部变量print\u name\u函数 在该函数范围内,该变量是对另一个变量的引用 作用 def包装器: 现在编写一个函数来做一些事情 教授: print_name_函数在这里您的函数正在调用一个作用域 顺便说一下,这是另一个变量 作用看看这个范围 变量是*title\u decorator* 现在,要返回参数函数,请返回另一个 还有其他一些行为 返回包装器 OBS:当包装器调用函数时,这是对对象的引用。记住这一点简单地说,Decorator函数用于增强函数的功能。请阅读我的代码注释,希望您理解这一点
您的问题是:decorator是如何知道print\u name\u函数的,或者它是如何工作的?您将函数print\u mike作为print\u name\u函数传递,并且带有括号的print\u name\u函数调用该函数。在Python中,函数是对象,所以您可以通过引用传递它们。@Awdweaden抱歉,我有点困惑。我认为需要定义函数,例如:def print_my_name。参数print\u name\u函数实际上是一个函数吗?对不起,我有点困惑。我认为需要定义函数,例如:def print_my_name。参数print\u name\u函数实际上是一个函数吗?对不起,我有点困惑。我认为需要定义函数,例如:def print_my_name。参数print\u name\u函数实际上是一个函数吗?它是对函数对象的引用。您可以在主作用域中定义print_my_name,并将对该函数的引用发送到title_decorator函数。在该函数范围title\u decorator中,print\u name\u函数引用该引用的值。
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 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```