python - 为什么 python 装饰器的结果是这样的..?
问题描述
这些天,我研究python装饰器,我的问题代码是这样的。
import functools
def my_decorator(func):
@functools.wraps(func)
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("hello!")
ret = my_decorator(say_hello)
ret()
实际上,我期待这个结果
Something is happening before the function is called.
hello!
Something is happening after the function is called.
但真正的输出是这样的。
Something is happening before the function is called.
Something is happening before the function is called.
hello!
Something is happening after the function is called.
Something is happening after the function is called.
有人能告诉我为什么会这样吗?
解决方案
当您应用这样的装饰器时:
@my_decorator
def say_hello():
它实际上在幕后做的是:
say_hello = my_decorator(say_hello)
所以如果你这样做:
ret = my_decorator(say_hello)
您实际上调用了两次装饰器,因此您看到的双重消息。
推荐阅读
- dataframe - 错误的 x 刻度标签 matplotlib
- material-design-in-xaml - Root DialogHost 给出一个空白窗口
- java - 依赖默认字段初始化 - 编程风格不好?
- r - 从多个页面抓取 html 节点
- jquery - 离子范围滑块不适用于中心标签
- javascript - 传递数组以填充数组
- kotlin - 具有多态 kotlinx 序列化的自定义序列化程序
- java - jenkinsfile 中的 docker run 忽略了黄瓜选项,但本地没有
- c++ - 两个错误消息说无法执行因为缺少文件(wxmsw312u_core_vc_custom.dll,wxbase312u_vc_custom.dll)如何解决
- azure - Azure DevOps 中的 Terraform local-exec Powershell 错误:运行 Connect-AzAccount 登录