如何为带参数的函数编写装饰器?
How to write a decorator for a function with an argument?
我想写一个装饰器来将主要功能的标准输出重定向到特定的日志文件。 main 函数接受的参数是 -item,我希望装饰器为 main 函数的每个项目分配不同的日志路径。我该如何实现?
目前我有:
def redirect_stdout(func):
def wrapper():
with open(f"{log_path}{item}.log", "w") as log, contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
func(item)
return wrapper()
@redirect_stdout
def main(item):
但我不确定 item 参数是如何进入装饰器的。谢谢!
您要查找的内容如下所示
def redirect_stdout(func):
def wrapper(item):
with open(f"{log_path}{item}.log", "w") as log, contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
func(item)
return wrapper
要了解其工作原理,您需要正确了解装饰器的工作原理。检查下面我试图解释装饰器是如何工作的。 ==>
我已经习惯了表示这等价于.
@redirect_stdout
def main(item):
pass
== >
def main(item):
pass
main = redirect_stdout(main) = wrapper
---------
main(item) => wrapper(item)
我想写一个装饰器来将主要功能的标准输出重定向到特定的日志文件。 main 函数接受的参数是 -item,我希望装饰器为 main 函数的每个项目分配不同的日志路径。我该如何实现?
目前我有:
def redirect_stdout(func):
def wrapper():
with open(f"{log_path}{item}.log", "w") as log, contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
func(item)
return wrapper()
@redirect_stdout
def main(item):
但我不确定 item 参数是如何进入装饰器的。谢谢!
您要查找的内容如下所示
def redirect_stdout(func):
def wrapper(item):
with open(f"{log_path}{item}.log", "w") as log, contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
func(item)
return wrapper
要了解其工作原理,您需要正确了解装饰器的工作原理。检查下面我试图解释装饰器是如何工作的。 ==>
我已经习惯了表示这等价于.
@redirect_stdout
def main(item):
pass
== >
def main(item):
pass
main = redirect_stdout(main) = wrapper
---------
main(item) => wrapper(item)