装饰器
装饰器的作用,就是封装一个函数,然后修改它,也就是在不改变原有功能代码的基础上,添加额外的功能。在python中所有的东西都是对象,函数可以作为参数进行传递。
下面是模拟装饰器功能的一段代码:
def my_decorator(func):
def decorator():
print('hello')
func()
print('goodbye')
return decorator
def my_test():
print('my_test')
my_test = my_decorator(my_test)
my_test()
运行结果:
python使用@来生成一个装饰器,我们将上面的代码用上@符号:
def my_decorator(func):
def decorator():
print('hello')
func()
print('goodbye')
return decorator
@my_decorator
def my_test():
print('my_test')
# my_test = my_decorator(my_test)
my_test()
运行结果: