修饰器就是一个普通的python函数,接受一个函数作为其唯一的参数, 并返回一个新函数(一般是传入函数的封装)。
下面的my_decorator就是一个简单的修饰函数:
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)
语法糖
Python allows you to use decorators in a simpler way with the @
symbol.
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
@my_decorator
def say_whee():
print("Whee!")
这里@my_decorator
就等效于上面的 say_whee = my_decorator(say_whee)
.
不同之处在于,@my_decorator在其所处模块作为包导入之后函数say_whee()未被调用之前其实就已经被解释器执行过了,即say_whee = my_decorator(say_whee) 是在from xxx import say_whee之后,在代码块中显性调用say_whee()之前就被执行了的。
推荐阅读 谈谈python修饰器