Xco*_*deX 3 python function decorator wrapper
我目前正在尝试了解装饰器是什么以及它们的用途。到目前为止,我了解到它们只是传递和返回函数作为参数的函数,它们的目的是修改函数而不修改原始函数。
我的问题与用于定义它们的经典结构有关。通常,您定义一个装饰器函数,并在其中定义另一个称为包装器的函数,该函数由装饰器函数返回。
所以我的问题是,为什么在装饰器内部创建包装器,而它可以只用一个函数来完成?这样做不是更“Pythonic”吗?
例如以下2段代码:
def country(func):
def wrapper_function():
print("The name of my favorite country is: ")
return func()
return wrapper_function
@country # == fav_country = country(fav)
def fav():
print("Sweden")
fav()
Run Code Online (Sandbox Code Playgroud)
输出:
我最喜欢的国家的名字是:
瑞典
def country(func):
print("The name of my favorite country is: ")
return func
@country # == fav_country = country(fav)
def fav():
print("Sweden")
fav()
Run Code Online (Sandbox Code Playgroud)
输出: 我最喜欢的国家的名字是:
瑞典
你是对的,装饰器只不过是一个以函数作为参数并返回函数的函数。但这两个:
def country1(func):
def wrapper_function():
print("The name of my favorite country is: ")
return func()
return wrapper_function
def country2(func):
print("The name of my favorite country is: ")
return func
Run Code Online (Sandbox Code Playgroud)
不等价。考虑
@country1
def fav1():
print("Sweden")
@country2
def fav2():
print("Sweden")
Run Code Online (Sandbox Code Playgroud)
看看当你打电话时会发生什么
fav1()
fav1()
fav1()
Run Code Online (Sandbox Code Playgroud)
和
fav2()
fav2()
fav2()
Run Code Online (Sandbox Code Playgroud)
您country2
不会修改原始函数,并且结果The name of my favorite country is:
仅在装饰过程中(在函数声明时)打印一次。当country1
更改装饰函数的行为时,您将看到该消息 3 次。