python - 装饰器中的这个函数如何在 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()
解决方案
把装饰器想象成一个返回另一个函数的函数。您要做的是在不更改其实现的情况下向函数添加行为。
在实践中,装饰器具有以下行为。
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:当包装器调用函数时,这是对对象的引用。记住这一点
推荐阅读
- python - 使用 `keras.utils.Sequence` 作为输入时,不支持 `y` 参数。错误
- oracle - ORA-00936: 缺少表达式
- javascript - 如何使特定选项出现在选择菜单中?
- r - 使用 model.matrix 的 One-hot 编码
- bash - 重新分发文件夹中的文件
- c++ - C ++中struct后双括号的含义?
- ssl - Windows 上的 Composer 安装程序错误:OpenSSL 因“证书验证失败”错误而失败
- ceph - cephfs 出现“只读文件系统”错误,如何处理?
- python - IndentationError: unindent 不匹配任何外部缩进
- amazon-web-services - 如何让 Terraform 等待 cloudinit 完成?