其他分享
首页 > 其他分享> > @函数装饰器

@函数装饰器

作者:互联网

装饰器

# 装饰器函数
def funcA(fc):
  print('this is funcA')
  # 执行传入的fc参数
  fc()
  return fc

@funcA
def funcB():
  print('this is funcB')
funcB()

output:
this is funcA
this is funcB
this is funcB

以上内容等价于:

# 装饰器函数
def funcA(fc):
  print('this is funcA')
  # 执行传入的fc参数
  fc()
  return fc

def funcB():
  print('this is funcB')
funcB = funcA(funcB)

即:funcB作为参数传给装饰器函数funcAfuncA的执行返回值赋值给funcB

由此可见,被“装饰”的函数取决于装饰器的返回值

实际上,所谓函数装饰器,就是通过装饰器函数,在不改变原函数的前提下,对函数的功能进行合理扩充。

带参的装饰器

def funcA(fc):
  def subFunc(input):
    print('funcA-subFunc:{}'.format(input))
  return subFunc

@funcA
def funcB(input):
  print('funcB:{}'.format(input))
funcB('函数装饰器')

output:
funcA-subFunc:函数装饰器

显然,在程序中调用的是funcB函数,但实际执行的是被装饰器嵌套的subFunc函数。
以上代码等价于:

def funcA(fc):
  def subFunc(input):
    print('funcA-subFunc:{}'.format(input))
  return subFunc

def funcB(input):
  print('funcB:{}'.format(input))
func = funcA(funcB)
func('函数装饰器')

output:
funcA-subFunc:函数装饰器

以上示例为函数只有一个参数的情况,若一个装饰器用于多个函数,该如何定义呢?

*args**kwargs 表示可以接受任意数量与类型的参数,可将其作为装饰器嵌套函数的参数。例如:

def funcA(fc):
  def subFunc(*args, **kwargs):
    print('funcA:{}'.format(*args, **kwargs))
  return subFunc
@funcA
def funcB(input):
  print('funcB:{}'.format(input))

@funcA
def funcC(input):
  print('funcC:{}'.format(input))
# 字符串
funcB('funcB')
# 整数
funcC(1)

outputs:
funcA:funcB
funcA:1

标签:函数,funcB,funcA,input,装饰,def
来源: https://www.cnblogs.com/ArdenWang/p/16112322.html