Loading

Python装饰器

装饰器的作用就是为已经存在的对象添加额外的功能

  1. 理解函数
  2. 在函数中定义函数
  3. 函数作为函数的返回值
  4. 函数作为参数传递给另一个函数
# 装饰器
def decorator(func):
	
    def inner():	# 在函数中定义函数
        print('inner函数被调用了')
        return func()
    return inner	# 函数作为函数的返回值

#被装饰函数
def foo():
	print('foo函数被调用了')
foo = decorator(foo)	# 函数作为参数传递给另一个函数
foo()
# output:
# inner函数被调用了
# foo函数被调用了
# 装饰器
def decorator(func):
	
    def inner():	# 在函数中定义函数
        print('inner函数被调用了')
        return func()
    return inner	# 函数作为函数的返回值

# 被装饰函数
@decorator
def foo():
    print('foo函数被调用了')
foo()
# output:
# inner函数被调用了
# foo函数被调用了

上述两段程序功能完全一样,@decorator的作用相当于foo = decorator(foo),将foo函数当做参数传递给decorator函数,将decorator函数的返回值inner函数赋值给foo函数,此时再调用foo函数相当于执行inner函数。(注意:函数后面加括号表示调用此函数,函数会执行,只写函数名则可把函数当成变量看待)

装饰器的作用即是在不改变foo函数的情况下,可以在inner函数中添加程序来增加其功能

posted @ 2020-12-15 20:23  紫曜花  阅读(70)  评论(0编辑  收藏  举报