【Python】Python装饰器 代码举例讲解

Python中的装饰器(decorator)可以不改变函数代码的基础上给函数增加额外功能。实现装饰器的几个关键点:

  1. 装饰器是修改其他函数的函数
  2. 使用 @ 语法将装饰器应用到函数上
## python www.itzhimei.com 代码
@decorator 
def func():
  pass
  1. 装饰器接收被装饰的函数作为参数,返回修改后的函数
## python www.itzhimei.com 代码
def decorator(func):

  def wrapper():
    # 额外功能代码
    func()

  return wrapper
  1. 使用内嵌包装函数来装饰函数
## python www.itzhimei.com 代码
def decorator(func):

  def wrapper():
    # 额外功能
    func()

  return wrapper
  1. 装饰器可以装饰类方法和静态方法
## python www.itzhimei.com 代码
@decorator
def func(self):
  pass

示例:计时装饰器

## python www.itzhimei.com 代码
import time

def timer(func):
  def wrapper():
    start = time.time()
    func()
    end = time.time()
    print(end - start)

  return wrapper

@timer
def test():
  print("testing...")

test()

装饰器是一个很强大和有用的工具,可以不修改被装饰函数的代码对其增加功能。