请问 func() 在 python 中在函数内部使用时意味着什么,例如下面的代码。
def identity_decorator(func):
def wrapper():
func()
return wrapper
func
是赋予函数 identity_decorator()
的参数。
表达式
func()
的意思是“调用分配给变量func
的函数。”
装饰器接受另一个函数作为参数,并返回一个新函数(定义为
wrapper
),该函数在运行时执行给定的函数func
。
我也有同样的疑问!您可以通过以下示例了解它是如何工作的:
def make_pretty(func):
def inner():
print("I got decorated")
func()
return inner
def ordinary():
print("I am ordinary")
pretty = make_pretty(ordinary)
pretty()
Output
I got decorated
I am ordinary
现在,当您删除 func() 并尝试重新运行它时:
def make_pretty(func):
def inner():
print("I got decorated")
return inner
def ordinary():
print("I am ordinary")
pretty = make_pretty(ordinary)
pretty()
Output
I got decorated
您会看到装饰函数没有被调用。请看这里https://www.programiz.com/python-programming/decorator