python - 在python中仅使用一个装饰器使用定义的属性并将n个属性传递给包装器
问题描述
我正在学习使用装饰器,但我不知道如何在不制作特定于函数的装饰器的情况下将已定义的属性传递给包装器。
假设我有一个装饰器:
def decorator(func):
def wrapper():
print("Before the function")
func()
print("After the function")
return wrapper
有了这个,我只能将它与只有定义属性或没有任何属性的函数一起使用,例如:
@decorator
def foo1(attribute1=10, attribute2=20):
print(attribute1, attribute2)
return
foo1()
但这让我无法运行:
foo1(1, 2)
有了这个问题,我也不能在没有相同数量的属性设置的不同函数上使用这个装饰器。
因此,有一种方法可以解决这个问题,而无需使用*args
和**kwargs
或至少无需调用如下所示的函数:foo((arg1, arg2, argn))
?因为它会让我无法定义任何属性。这是我唯一的约束。
谢谢。
解决方案
包装器必须接受参数(因为它替换了绑定到修饰名称的原始函数),并且这些参数必须传递给func
.
def decorator(func):
def wrapper(*args, **kwargs):
print("Before the function")
func(*args, **kwargs)
print("After the function")
return wrapper
推荐阅读
- javascript - 如果应用程序正在侦听“localhost”,我们如何访问网络外部的节点服务器?
- python - 如何将另一个脚本的控制台打印从我的 python 脚本中传输到文件?
- maven - Spark-submit 没有使用我项目的 protobuf 版本
- ios - 在 UIScrollView 中嵌入 UIStackView 时出现的问题
- python - 对 __iter__(self) 和 iter() 感到困惑
- postgresql - 如何获得更改运行时参数的权限?
- linux - 如何将我的主机中的文件夹挂载到自定义 docker 映像,在目录中使用 Dockerfile 进行设置?
- c - C中显示文件记录小问题的功能
- google-play - 无法修复 Eclipse 中的 Libpng 问题
- javascript - html5 音量不变