python 装饰器有问题
having issue with python decorator
我试图使用 https://realpython.com/blog/python/primer-on-python-decorators/ 上的优秀教程来了解更多关于 Python 装饰器的信息。
我试图偏离剧本,运行遇到了一些问题。代码如下。基本上,当我 运行 下面的脚本时,第一个函数调用
time_print_function() 按预期执行。
但是我在下一个函数调用中遇到错误 my_decorator(print(datetime.datetime.now()))()
我预计这会产生与 time_print_function()
相同的输出
代码为
def my_decorator(some_function):
def wrapper(*args):
print "Something is happening before some_function() is called."
if args:
some_function(args)
else:
some_function()
print "Something is happening after some_function() is called."
return wrapper
@my_decorator
def time_print_function():
print(datetime.datetime.now())
time_print_function()
my_decorator(print(datetime.datetime.now()))()
问题是这个表达式:
my_decorator(print(datetime.datetime.now()))()
在将打印函数作为参数传递给
my_decorator
电话。 my_decorator
接收 return 值
print
的 None 并尝试调用它,产生错误
(None显然是不可调用的)。
装饰器的参数应该是一个函数——你可以
使用 lambda 创建一个内联,例如:
my_decorator(lambda: print(datetime.datetime.now()) )()
我试图使用 https://realpython.com/blog/python/primer-on-python-decorators/ 上的优秀教程来了解更多关于 Python 装饰器的信息。
我试图偏离剧本,运行遇到了一些问题。代码如下。基本上,当我 运行 下面的脚本时,第一个函数调用 time_print_function() 按预期执行。
但是我在下一个函数调用中遇到错误 my_decorator(print(datetime.datetime.now()))()
我预计这会产生与 time_print_function()
相同的输出代码为
def my_decorator(some_function):
def wrapper(*args):
print "Something is happening before some_function() is called."
if args:
some_function(args)
else:
some_function()
print "Something is happening after some_function() is called."
return wrapper
@my_decorator
def time_print_function():
print(datetime.datetime.now())
time_print_function()
my_decorator(print(datetime.datetime.now()))()
问题是这个表达式:
my_decorator(print(datetime.datetime.now()))()
在将打印函数作为参数传递给
my_decorator
电话。 my_decorator
接收 return 值
print
的 None 并尝试调用它,产生错误
(None显然是不可调用的)。
装饰器的参数应该是一个函数——你可以 使用 lambda 创建一个内联,例如:
my_decorator(lambda: print(datetime.datetime.now()) )()