我在这里浏览此装饰器教程: https://www.python-kurs.eu/python3_dekorateure.php 我不确定为什么装饰器有时会打印范围内的内容,而有时却不会。下面的代码。
def morning_greeting(func):
def function_wrapper(x):
print("Good morning, " + func.__name__ + " returns:")
func(x)
return function_wrapper
@morning_greeting
def foo(x):
print(42)
foo("Hi")
此打印:
Good morning, foo returns:
42
我尝试了相同的代码,但在function_wrapper(x)内包含“ return func(x)”,它也给出了此打印信息。
然后是此代码:
def greeting(func):
def function_wrapper(x):
""" function_wrapper of greeting """
print("Hi, " + func.__name__ + " returns:")
return func(x)
return function_wrapper
@greeting
def f(x):
""" just some silly function """
return x + 4
f(10)
print("function name: " + f.__name__)
print("docstring: " + f.__doc__)
print("module name: " + f.__module__)
此打印:
Hi, f returns:
function name: function_wrapper
docstring: function_wrapper of greeting
module name: greeting_decorator
第二行代码为什么不打印f(10)为14,即第一行显示“嗨,f返回:14”?
答案 0 :(得分:0)
您可能想看看装饰者的一些更好的教程。 functools
模块具有一个有用的装饰器,称为wraps
(很好地解释了here),该装饰器保留了函数__name__
和__doc__
的属性:
from functools import wraps
def greeting(func):
@wraps(func)
def function_wrapper(x):
""" function_wrapper of greeting """
print("Hi, " + func.__name__ + " returns:")
return func(x)
return function_wrapper
@greeting
def f(x):
""" just some silly function """
return x + 4
f(10)
print("function name: " + f.__name__)
print("docstring: " + f.__doc__)
print("module name: " + f.__module__)
>> Hi, f returns:
function name: function_wrapper
docstring: function_wrapper of greeting
module name: __main__