python装饰器的使用

前言:

  在web开发过程中,经常会遇到数据查询慢的问题,对于查询一些时效性不是特别强的数据可以将数据缓存到redis中, 查询的时候直接到缓存中读取数据,这样就可以大大加快查询速度。
  但是在开发前,事先没有增加缓存这个功能,并且需要增加缓存功能的地方又有很多,为了在不改变原有代码的基础上添加新的功能,这就要用到python的装饰器。这里简要记录一下装饰器的使用!

说明:

  弄清了装饰器函数的执行流程,以及参数如何传递等,装饰器的使用基本上就差不多了。这里通过一下几步来学习装饰器的使用:
  1.装饰器的引入;
  2.被装饰函数无参的装饰器;
  3.被装饰函数带参的装饰器;
  4.装饰器带参的装饰器。

装饰器的引入
# coding:utf-8

import time

def decorator(fun):
    """统计函数的运行时间"""
    start = time.time()
    fun()
    end = time.time()
    print end - start

def do_something():
    for i in range(5):
        time.sleep(1)
        
decorator(do_something)

代码解读:
  将do_something函数作为decorator函数的参数传入,在decorator函数中实现新的业务逻辑,并调用do_something函数, 这样就实现了在添加新功能的同时,不改变原有代码的逻辑,该写法不够简洁。

被装饰函数无参的装饰器
# coding:utf-8

import time

def decorator(fun):
    def wrapper():
        start = time.time()
        fun()
        end = time.time()
        print end - start

    return wrapper

@decorator
def do_something():
    for i in range(5):
        time.sleep(1)

do_something()
# 等价于:decorator(do_something)()

代码解读:
do_something()添加装饰器后,等价于do_something() = decorator(do_something)(),执行过程如下:

  • 执行decorator方法,并将do_something方法作为参数传递;
  • 返回内层函数wrapper的引用;
  • 执行wrapper方法,等价于decorator(do_something)()
被装饰函数带参的装饰器
# coding:utf-8

import time

def decorator(fun):
    def wrapper(*args, **kwargs):
        start = time.time()
        fun(*args, **kwargs)
        end = time.time()
        print end - start

    return wrapper

@decorator
def do_something(times):
    for i in range(times):
        time.sleep(1)

do_something(5)
# 等价于:decorator(do_something)(5)

代码解读:
do_something(params)添加装饰器后,等价于do_something(params) = decorator(do_something)(params),执行过程如下:

  • 执行decorator方法,并将do_something方法作为参数传递;
  • 返回内层函数wrapper的引用;
  • 执行wrapper方法,等价于decorator(do_something)(params),可知,参数是通过内层函数wrapper传递进来的。
装饰器带参的装饰器
# coding:utf-8

import time

def decorator(name="带参装饰器"):
    def wrapper(fun):
        def inner(*args, **kwargs):
            start = time.time()
            fun(*args, **kwargs)
            end = time.time()
            print end - start
            print name
        return inner
    return wrapper

@decorator(name="带参装饰器")
def do_something(times):
    for i in range(times):
        time.sleep(1)

do_something(5)
# 等价于:decorator("带参装饰器")(do_something)(params)

代码解读:
do_something(params)添加装饰器后,等价于do_something(params) = decorator("带参装饰器")(do_something)(params),执行过程如下:

  • 执行decorator方法,并传递参数name,
  • 返回内层函数wrapper的引用,wrapper = decorator("带参装饰器")
  • 执行wrapper方法, 并传递do_something方法的引用,返回inner函数的引用,inner = decorator("带参装饰器")(do_something)
  • 执行inner方法,并传递参数params,实现inner方法的内部逻辑, 即:decorator("带参装饰器")(do_something)(params)

喜欢点个赞!

你可能感兴趣的:(python装饰器的使用)