【发布时间】:2019-06-23 11:21:08
【问题描述】:
我正在学习如何在 Python 中使用装饰器,并且对它有深入的了解,但我有一个问题 - 为什么我不能将装饰器用于内置函数?
为什么会这样:
def decorator1(func):
def inner(*args, **kwargs):
print("<>=========================<>")
func(*args, **kwargs)
print("<>=========================<>")
return inner
@decorator1
def greet():
print("Hello!")
greet()
不是这个?:
def decorator1(func):
def inner(*args, **kwargs):
print("<>=========================<>")
func(*args, **kwargs)
print("<>=========================<>")
return inner
@decorator1
print("Hello!")
是不是因为print函数是现场执行的,而greet()函数只定义了,只在@decorator1之后运行?
【问题讨论】:
-
因为装饰器装饰的是函数,而不是函数调用
-
装饰器可以很好地使用内置函数。还有其他问题。
-
@MartijnPieters 这对我不起作用;我在 Mac OS Mojave 上使用 Python 3.7.1...
-
我没有说你的方法有效。 :-) 只要你知道如何应用它们,装饰器就可以处理内置函数。
标签: python decorator python-decorators built-in