Python笔记:Python装饰器

目录

  • python简单装饰器
    • functools()
  • 带参数的装饰器
  • 装饰器的嵌套
    • 嵌套示例
  • 类装饰器
  • 装饰器使用实例
    • 统计函数执行时间
    • 登录认证
  • 系列文章

装饰器是通过装饰器函数修改原函数的一些功能而不需要修改原函数,在很多场景可以用到它,比如① 执行某个测试用例之前,判断是否需要登录或者执行某些特定操作;② 统计某个函数的执行时间;③ 判断输入合法性等。合理使用装饰器可以极大地提高程序的可读性以及运行效率。本文将介绍Python装饰器的使用方法。

python简单装饰器

python装饰器可以定义如下:

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print('this is wrapper')
        func(*args, **kwargs)
        print('bye')
    return wrapper

def test_decorator(message):
    print(message)

decorator = my_decorator(test_decorator)
decorator('hello world')

输出:

this is wrapper
hello world
bye

python解释器将test_decorator函数作为参数传递给my_decorator函数,并指向了内部函数 wrapper(),内部函数 wrapper() 又会调用原函数 test_decorator(),所以decorator()的执行会先打印’this is wrapper’,然后打印’hello world’, test_decorator()执行完成后,打印 ‘bye’ ,*args和**kwargs,表示接受任意数量和类型的参数。

装饰器 my_decorator() 把真正需要执行的函数 test_decorator() 包裹在其中,并且改变了它的行为,但是原函数 test_decorator() 不变。

一般使用如下形式使用装饰器:

@my_decorator
def test_decorator(message):
    print(message)

test_decorator('hello world')

@my_decorator就相当于 decorator = my_decorator(test_decorator) 语句。

functools()

内置装饰器@functools.wrap可用于保留原函数的元信息(将原函数的元信息,拷贝到对应的装饰器函数里)。先来看看没有使用functools的情况:

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print('this is wrapper')
        func(*args, **kwargs)
    return wrapper

@my_decorator
def test_decorator(message):
    print(message)

test_decorator('hello world')
print(test_decorator.__name__)
print("######")
help(test_decorator)

输出:

this is wrapper
hello world
wrapper
######
Help on function wrapper in module __main__:

wrapper(*args, **kwargs

你可能感兴趣的:(#,Python笔记,python,装饰器)