Python装饰器用法实例分析

蓝鲸
蓝鲸
发布时间:2026-10-13 | 3人浏览过
原创

本文深入解析Python装饰器的核心用法,通过无参、单参及多参数场景的完整代码示例,展示如何构建通用的日志记录装饰器。重点讲解带参装饰器的嵌套实现原理,帮助开发者掌握函数包装与参数传递机制,提升代码复用能力。

本文通过具体实例解析Python中装饰器的使用方法,供读者参考学习。

无参数的装饰器实现

#coding=utf-8
def log(func):
  def wrapper():
    print 'before calling ',func.__name__
    func()
    print 'end calling ',func.__name__
  return wrapper
@log
def hello():
  print 'hello'
@log
def hello2(name):
  print 'hello',name
if __name__=='__main__':
  hello()

运行结果如下:

before calling hello hello end calling hello

带参数的装饰器示例:

#coding=utf-8
def log(func):
  def wrapper(name):
    print 'before calling ',func.__name__
    func(name)
    print 'end calling ',func.__name__
  return wrapper
@log
def hello(name):
  print 'hello',name
@log
def hello2(name):
  print 'hello',name
if __name__=='__main__':
  hello('haha')

运行结果:

before calling hello hello haha end calling hello

处理多个参数的情况:

#coding=utf-8
def log(func):
  '''
  *无名字的参数
  **有名字的参数
  :param func:
  :return:
  '''
  def wrapper(*args,**kvargs):
    print 'before calling ',func.__name__
    print 'args',args,'kvargs',kvargs
    func(*args,**kvargs)
    print 'end calling ',func.__name__
  return wrapper
@log
def hello(name,age):
  print 'hello',name,age
@log
def hello2(name):
  print 'hello',name
if __name__=='__main__':
  hello('haha',2)
  hello(name='hehe',age=3)

输出结果:

end calling hello before calling hello args () kvargs {'age': 3, 'name': 'hehe'} hello hehe 3 end calling hello

装饰器内部包含参数的场景

其本质在于嵌套函数的应用

#coding=utf-8
def log(level,*args,**kvargs):
  def inner(func):
    def wrapper(*args,**kvargs):
      print level,'before calling ',func.__name__
      print level,'args',args,'kvargs',kvargs
      func(*args,**kvargs)
      print level,'end calling ',func.__name__
    return wrapper
  return inner
@log(level='INFO')
def hello(name,age):
  print 'hello',name,age
@log
def hello2(name):
  print 'hello',name
if __name__=='__main__':
  hello('haha',2)

运行输出:

INFO before calling hello INFO args ('haha', 2) kvargs {} hello haha 2 INFO end calling hello

更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表