python - 我们什么时候调用 de-facto 装饰器中的内部函数?
问题描述
我正在努力理解 Python 中的比较器,其中一个教程建议查看以下示例:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
def say_whee():
print("Whee!")
say_whee = my_decorator(say_whee)
say_whee()
当我调用say_whee()
它时,它会打印以下内容:
Something is happening before the function is called.
Whee!
Something is happening after the function is called.
我隐约明白为什么它会打印这些行,但我不明白我们什么时候打电话wrapper()
所以它可以打印这些行。
我们什么时候打电话wrapper()
?
解决方案
您返回wrapper
并将其分配给say_wee
:
say_whee = my_decorator(say_whee)
所以在这里调用它:
say_whee()
你自己看:
>>> def my_decorator(func):
... def wrapper():
... print("Something is happening before the function is called.")
... func()
... print("Something is happening after the function is called.")
... return wrapper
...
>>> def say_whee():
... print("Whee!")
...
>>> say_whee = my_decorator(say_whee)
>>>
>>> say_whee
<function my_decorator.<locals>.wrapper at 0x1040d89d8>
>>> say_whee.__name__
'wrapper'
推荐阅读
- twitter-bootstrap - Bootstrap:并排标签
- sql-server - SQL Server 存储过程仅适用于本地重新声明的变量;不是传递给过程的变量
- php - PHP 选择选项值保护
- azure - Azure 流分析:多个 Windows + JOINS
- scala - 为什么隐式类中的函数不可用?
- angular - @Input Array 如果在 Angular 组件上设置了多个
- r - 使用 R 和 tidyverse 将 tidy 表转换为深度嵌套列表
- ibm-cloud-private - 节点支持的 ICP 角色配置有哪些?
- java - 读取 csv 文件但带有空字符串 []
- json - 如何在 Angular 5 中为数据表实现数据源