亲宝软件园·资讯

展开

python 装饰器 python 装饰器的使用示例

南方的墙 人气:0
想了解python 装饰器的使用示例的相关内容吗,南方的墙在本文为您仔细讲解python 装饰器的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:python,装饰器,python,装饰器示例,下面大家一起来学习吧。

无参修饰 ,无参数时不需要调用

def log1(func):
  func()
@log1
def test():
  print('test:')

有参修饰

def log2(func):
  def inner(*args, **kwargs):
    func(*args, **kwargs)
  return inner
@log2
def test(num):
  print('testlog2:',num,test.__name__)
test(20) #相当于log(test(20))

@wraps可以保证装饰器修饰的函数的name的值保持不变

不带参数的装饰器

def log3(func):
  @wraps(func)
  def inner(*args, **kwargs,):
    func(*args, **kwargs)
  return inner
@log3
def test(num):
  print('testlog3:',num,test.__name__)
test(30) #相当于log(test(30))

带参数的装饰器

def log4(level):
  def log(func):
    @wraps(func)
    def inner(*args, **kwargs,):
      if level == "warn":
        print("%s is running" % func.__name__)
      func(*args, **kwargs)
    return inner
  return log
@log4(level="warn")
def test(num):
  print('testlog4:', num, test.__name__)
test(40)

实现带参数和不带参数的装饰器自适应

def log(arg):
  if callable(arg): # 判断参入的参数是否是函数,不带参数的装饰器调用这个分支
    def log3(func):
      @wraps(func)
      def inner(*args, **kwargs, ):
        func(*args, **kwargs)
      return inner
    return log3
  else:
    def log4(func):
      @wraps(func)
      def inner(*args, **kwargs,):
        if arg == "warn":
          print("%s is running" % func.__name__)
        func(*args, **kwargs)
      return inner
    return log4
@log(arg=None)
def test(num):
  print('testlog:', num, test.__name__)
test(0)

返回入参出参

def log5(func):
  def inner(*args, **kwargs):
    print('入参:',func.__name__, args, kwargs)
    res =func(*args, **kwargs)
    print('出参:',func.__name__, res)
    return res
  return inner
@log5
def test(num):
  print('testlog5:', num, test.__name__)
  return num
print(test(50))

类装饰器

class Loging:
  def __init__(self,level):
    self.level = level

  def __call__(self,func):
    @wraps(func)
    def inner(*args, **kwargs):
      if self.level == "warn":
        self.notify(func)
      func(*args, **kwargs)
    return inner

  def notify(self,func):
    print ("%s is running" % func.__name__)


@Loging(level="warn")
def test(num):
  print('testLoging:', num, test.__name__)
test(0)

加载全部内容

相关教程
猜你喜欢
用户评论