装饰器其实是闭包的一种,如果有重复功能需要实现的话,装饰器是个不错的选择。比如每个函数需要添加一个提示开始的功能:
代码语言:javascript复制def start(func):
def wrapper():
print("Now function {} starts!".format(func.__name__))
return func()
return wrapper
def greet():
print("Hello, everyone!")
def morning():
print("Good Morning!")
greet = start(greet)
greet()
morning = start(morning)
morning()
我们需要这两个函数的开始的提醒,这样写可以避免在greet和morning函数中重复的写
代码语言:javascript复制print("Now function {} starts!".format(func.__name__))
这句话,不过这样写还可以进一步省略,即:
代码语言:javascript复制def start(func):
def wrapper():
print("Now function {} starts!".format(func.__name__))
return func()
return wrapper
@start
def greet():
print("Hello, everyone!")
@start
def morning():
print("Good Morning!")
greet()
morning()
如果function需要参数的话可以用*args和**kwargs:
代码语言:javascript复制def start(func):
def wrapper(*args, **kwargs):
print("Now function {} starts!".format(func.__name__))
return func(*args, **kwargs)
return wrapper
@start
def greet(name):
print("Hello, {}!".format(name))
@start
def morning(name):
print("Good Morning, {}!".format(name))
greet('Kura')
morning('Kura')
返回: Now function greet starts! Hello, Kura! Now function morning starts! Good Morning, Kura!