• python 装饰器


    前言

    装饰器、迭代器和生成器被称为python三大器,本文主要交流下装饰器的一些知识

    一、什么是装饰器

    1. 用于拓展原来函数功能的一种函数
    2. 返回函数的函数
    3. 在不用更改原函数的代码的前提下给函数增加新的功能

    二、简单装饰器

    先来一个例子,上代码

     1 def log(func):
     2     """实现装饰器"""
     3 
     4     def wrapper():
     5         print('start...')
     6         func()
     7         print('end...')
     8 
     9     return wrapper
    10 
    11 
    12 @log  # 使用装饰器
    13 def test():
    14     print("hello world")
    15 
    16 
    17 if __name__ == "__main__":
    18     test()

    运行结果

    1 D:\develop\Envs\test_django\Scripts\python.exe D:/develop/test_django/hello/implements/test_decorator.py
    2 start...
    3 hello world
    4 end...
    5 
    6 Process finished with exit code 0

    log就是一个最简单的不带参数、不带返回值的装饰器,一个函数可以有多个装饰器吗?下面我们测试下

     1 def log(func):
     2     """实现装饰器"""
     3 
     4     def wrapper():
     5         print('start...')
     6         func()
     7         print('end...')
     8 
     9     return wrapper
    10 
    11 
    12 def log2(func):
    13     """实现装饰器2"""
    14 
    15     def wrapper():
    16         print('log2 start ...')
    17         func()
    18         print('log2 end ...')
    19 
    20     return wrapper
    21 
    22 
    23 @log  # 使用装饰器
    24 @log2  # 使用装饰器2
    25 def test():
    26     print("hello world")
    27 
    28 
    29 if __name__ == "__main__":
    30     test()

    运行结果

    1 D:\develop\Envs\test_django\Scripts\python.exe D:/develop/test_django/hello/implements/test_decorator.py
    2 start...
    3 log2 start ...
    4 hello world
    5 log2 end ...
    6 end...
    7 
    8 Process finished with exit code 0

    所以一个函数支持添加多个装饰器,并且装饰器添加的顺序决定了执行的顺序

    三、带返回值的装饰器

    函数带了参数时并且需要有返回值时,简单装饰器就满足不了需求了,所以需要带返回值的装饰器,代码如下

     1 def decorator(func):
     2     def wrapper(*args,**kwargs):
     3         print('start----')
     4         res =func(*args,**kwargs)
     5         print('end----')
     6         return res
     7     return wrapper
     8 
     9 @decorator
    10 def sum(a, b):
    11     return a + b
    12 if __name__ == '__main__':
    13     r = sum(3,2)
    14     print(r)

    运行结果

     1 D:\develop\Envs\test_django\Scripts\python.exe D:/develop/test_django/hello/implements/decorator_s1.py 2 start---- 3 end---- 4 5 5 Process finished with exit code 0 

    这里使用魔法参数,实现了带返回值时的装饰器,那如果需要在装饰器里面展示出对应的信息呢,比如a调用装饰器,就返回a的信息,b调用装饰器就返回b的信息,此时就需要用到带参数的装饰器

     1 def log(name=None):
     2     def decorator(func):
     3         def wrapper(*args, **kwargs):
     4             print('{0} start ...'.format(name))
     5             rest = func(*args, **kwargs)
     6             # print(args)
     7             # print(kwargs)
     8             print('{0} end ...'.format(name))
     9             return rest
    10 
    11         return wrapper
    12 
    13     return decorator
    14 @log('you')
    15 def sum(a, b):
    16     """带参数和返回值的函数"""
    17     return a + b
    18 
    19 
    20 if __name__ == "__main__":
    21     r = sum(1, 2)
    22     print(r)

    运行结果

    1 D:\develop\Envs\test_django\Scripts\python.exe D:/develop/test_django/hello/implements/decorator_higer.py
    2 you start ...
    3 you end ...
    4 3
    5 
    6 Process finished with exit code 0

    装饰器的使用就介绍到这里啦,汇总如下:

    装饰器的作用:

    1. 用于拓展原来函数功能的一种函数
    2. 返回函数的函数
    3. 在不用更改原函数的代码的前提下给函数增加新的功能

    本文有易到难介绍了几种装饰器类型:

    1. 简单装饰器
    2. 带返回值的装饰器
    3. 带参数的装饰器
  • 相关阅读:
    pytorch-VGG网络
    pytorch-Alexnet 网络
    pytorch-LeNet网络
    硬链接与软链接有什么不同(ln)
    联想《拯救者》U盘UEFI启动装win7[完美激活](4)
    笔记本键盘、触控板锁定技巧(3)
    BridgePattern(23种设计模式之一)
    AdapterPattern(23种设计模式之一)
    Arduino Wire.h(IIC)库函数详解
    进制表示法
  • 原文地址:https://www.cnblogs.com/sunnydev/p/15831555.html
Copyright © 2020-2023  润新知