我正在努力理解Python中的比较器,其中一个教程建议查看以下示例:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
def say_whee():
print("Whee!")
say_whee = my_decorator(say_whee)
say_whee()
当我致电say_whee()
时,它会打印以下内容:
Something is happening before the function is called.
Whee!
Something is happening after the function is called.
我模糊地理解了为什么它会打印这些行,但是我不知道何时确切地调用wrapper()
,因此它可以打印这些行。
我们什么时候叫wrapper()
?
答案 0 :(得分:1)
您返回wrapper
并将其分配给say_wee
:
say_whee = my_decorator(say_whee)
因此它在这里被称为
say_whee()
亲自看看:
>>> def my_decorator(func):
... def wrapper():
... print("Something is happening before the function is called.")
... func()
... print("Something is happening after the function is called.")
... return wrapper
...
>>> def say_whee():
... print("Whee!")
...
>>> say_whee = my_decorator(say_whee)
>>>
>>> say_whee
<function my_decorator.<locals>.wrapper at 0x1040d89d8>
>>> say_whee.__name__
'wrapper'